Global variable between ROOT and python

Hello,

I modified the pyROOT tutorial example to add a global variable before the function Linear:

global aux
class Linear:
    def __call__( self, x, par ):
        return aux*par[0] + x[0]*par[1]

# create a linear function for fitting
f = TF1( 'pyf3', Linear(), -1., 1., 2 )

But the global variable ‘aux’ dosen’t pass to ROOT TF1.

Traceback (most recent call last):
File “”, line 4, in call
NameError: global name ‘aux’ is not defined

Is there a way to do this ?
Thanks
Cheers,
Olivier

Olivier,

this declaration:global aux
doesn’t create a global variable. It just tells the interpreter, that the first time that it sees “aux” in any scope, it will keep it in the global scope. In your case, the first time is when it is used in your call method. However, you have not defined it at that point yet, and a variable that hasn’t been defined yet, can not be used.

Typically, the “global” declaration is only useful inside a function, seldom is it useful at the module level. If, as here, you just want “aux” to be seen in call, all you have to do is define it. For example:[code]aux = 1 # define aux to be 1
class Linear:
def call( self, x, par ):
return aux*par[0] + x[0]*par[1]

create a linear function for fitting

f = TF1( ‘pyf3’, Linear(), -1., 1., 2 )[/code]

HTH,
Wim

Python throwing that error because it’s looking for a global variable that doesn’t exist. Before you use the a global variable in your function for reading, it must be first initialized somewhere: either outside of the function or inside it.