problem with global variable in a module

Duncan Booth duncan.booth at invalid.invalid
Sat Nov 25 10:13:03 EST 2006


"hollowspook" <hollowspook at gmail.com> wrote:

> 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. 

The global statement makes a name global to a module, it doesn't make it 
global to the entire program. The function aa is in module test, the 
statements you entered in the shell are in a different module called 
__main__.

The particular form of import you used may also be confusing you: just 
because you imported '*' doesn't change the function: 'aa' was defined in 
the module 'test' and that is where it still looks for its global 
variables, all the import did was define a new name 'aa' in the __main__ 
module which refers to the same function object as 'aa' in 'test'.




More information about the Python-list mailing list