Make variable global

Bruno Desthuilliers bdesth.quelquechose at free.quelquepart.fr
Wed Mar 21 22:09:39 CET 2007


abcd a écrit :
> I have a file, "a.py"
> 
> blah = None
> def go():
>     global blah
>     blah = 5
> 
>>From the python interpreter I try....
> 
> 
>>>>from a import *
>>>>blah
>>>>go()
>>>>blah
>>>>
> 
> 
> ...i was hoping to see "5" get printed out the second time I displayed
> blah, but it doesn't.  Now, if I type this same code directly into the
> python interpreter it works as i was hoping.  what i am missing?

In Python, 'global' means 'module level'. And 'variables' are 
name:object bindings in a namespace (mostly function, class or module). 
The way you import blah and go from module a creates two names (blah and 
go) in the current namespace, and bind these names to resp. a.blah and 
a.go. The fact that go rebinds a.blah doesn't impact current namespace's 
blah.

The following session may help you understanding what happens:

 >>> from a import *
 >>> dir()
['__builtins__', '__doc__', '__name__', 'blah', 'go']
 >>> import a
 >>> dir()
['__builtins__', '__doc__', '__name__', 'a', 'blah', 'go']
 >>> dir(a)
['__builtins__', '__doc__', '__file__', '__name__', 'blah', 'go']
 >>> go is a.go
True
 >>> go()
 >>> blah
 >>> a.blah
5
 >>>

Note that rebinding a name and mutating a (mutable) object are two 
distinct operations:

# b.py
blah = ['42']
def go():
     blah[0] = "yo"

def gotcha():
     global blah
     blah = ['gotcha']

 >>> from b import *
 >>> import b
 >>> blah
['42']
 >>> blah is b.blah
True
 >>> go()
 >>> blah
['yo']
 >>> b.blah
['yo']
 >>> blah is b.blah
True
 >>> gotcha()
 >>> blah
['yo']
 >>> b.blah
['gotcha']
 >>>

To make a long story short:
1/ avoid globals whenever possible
2/ when using (module) globals, either use them as pseudoconstants or as 
module's 'private' variables (IOW : only functions from the same module 
can modify/rebind them).

HTH



More information about the Python-list mailing list