global variable not seen (bug?)

Mike Meyer mwm at mired.org
Wed Jan 8 12:14:36 EST 2003


Michal Vitecek <fuf at mageo.cz> writes:

>  hello everyone,
> 
>  i've encountered a strange problem with accessing a global variable
>  from imported module. the imported module (file imported.py) contains:
>  
> ---imported.py start---
>  def someFunction():
>     global GLOBAL_VARIABLE
> 
>     print GLOBAL_VARIABLE
> ---imported.py end---
> 
>  and now the session copy:
> 
> ---session start---
> Python 2.2.1 (#4, Sep  4 2002, 13:43:54) 
> [GCC 2.95.3 20010315 (release)] on linux2
> Type "help", "copyright", "credits" or "license" for more information.
> >>> GLOBAL_VARIABLE = 'some value'
> >>> from imported import *
> >>> dir()
> ['GLOBAL_VARIABLE', '__builtins__', '__doc__', '__name__', 'someFunction']
> >>> someFunction()
> Traceback (most recent call last):
>   File "<stdin>", line 1, in ?
>   File "imported.py", line 4, in someFunction
>     print GLOBAL_VARIABLE
> NameError: global name 'GLOBAL_VARIABLE' is not defined
> >>> 
> ---session end---
> 
>  what's the problem here? it seems to me like this is a bug in python.

The global statement doesn't declare a variable, it tells the
interpreter to look in the global namespace for the variable. Since it
isn't there, the name is going to be undefined. Try doing
"GLOBAL_VARIABLE = 1" in your interpreter before you infoke
someFunction().

        <mike
-- 
Mike Meyer <mwm at mired.org>			http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.




More information about the Python-list mailing list