problem with global variable in a module

Diez B. Roggisch deets at nospam.web.de
Sat Nov 25 10:21:34 EST 2006


hollowspook schrieb:
> def aa():
>     global b
>     b=b+1
>     print b
> 
> b=1
> aa()
> 
> The above code runs well in python shell.
> 
> However I  have a problem as follows.
> 
> new a file named test.py
> ------------------------------------------------------------------------
> 
> def aa():
>     global b
>     b=b+1
>     print b
> -------------------------------------------------------------------------
> 
> Then in python shell,
> 
> from test import *
> b=1
> aa()
> 
> The error message is :
> Traceback (most recent call last):
>   File "<interactive input>", line 1, in ?
>   File "test.py", line 3, in aa
>     b=b+1
> NameError: global name 'b' is not defined
> 
> Why this happens? Please do me a favor. 

Because python does not know "real" globals - globals are always only
global on a module level. Now using the "from module import *"-syntax
asks for trouble. Because your global b above is global to the
__main__-module, not to the module test. But the aa-function expects it
to live in tests.

To make your example work, do it as this:

import test

test.b = 1
test.aa()


See
http://effbot.org/pyfaq/tutor-whats-the-difference-between-import-foo-and-from-foo-import.htm

Diez



More information about the Python-list mailing list