Possible Duplicate:
Using global variables in a function other than the one that created them
I'm using functions so that my program won't be a mess but I don't know how to make a local variable into global.
This question is related to
python
function
global-variables
local
You could use module scope. Say you have a module called utils
:
f_value = 'foo'
def f():
return f_value
f_value
is a module attribute that can be modified by any other module that imports it. As modules are singletons, any change to utils
from one module will be accessible to all other modules that have it imported:
>> import utils
>> utils.f()
'foo'
>> utils.f_value = 'bar'
>> utils.f()
'bar'
Note that you can import the function by name:
>> import utils
>> from utils import f
>> utils.f_value = 'bar'
>> f()
'bar'
But not the attribute:
>> from utils import f, f_value
>> f_value = 'bar'
>> f()
'foo'
This is because you're labeling the object referenced by the module attribute as f_value
in the local scope, but then rebinding it to the string bar
, while the function f
is still referring to the module attribute.
Simply declare your variable outside any function:
globalValue = 1
def f(x):
print(globalValue + x)
If you need to assign to the global from within the function, use the global
statement:
def f(x):
global globalValue
print(globalValue + x)
globalValue += 1
If you need access to the internal states of a function, you're possibly better off using a class. You can make a class instance behave like a function by making it a callable, which is done by defining __call__
:
class StatefulFunction( object ):
def __init__( self ):
self.public_value = 'foo'
def __call__( self ):
return self.public_value
>> f = StatefulFunction()
>> f()
`foo`
>> f.public_value = 'bar'
>> f()
`bar`
Using globals will also make your program a mess - I suggest you try very hard to avoid them. That said, "global" is a keyword in python, so you can designate a particular variable as a global, like so:
def foo():
global bar
bar = 32
I should mention that it is extremely rare for the 'global' keyword to be used, so I seriously suggest rethinking your design.
Source: Stackoverflow.com