global variable not seen (bug?)
Peter Hansen
peter at engcorp.com
Wed Jan 8 12:03:02 EST 2003
Michal Vitecek wrote:
>
> 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.
"Globals" are not really *global* in Python, they are visible only
throughout the module in which they are defined, not throughout the
entire application.
You've defined "GLOBAL_VARIABLE" in the module used for the interactive
interpreter (well, I think that's roughly what happens... it's close
enough for this discussion) but someFunction() is defined in another
module which has its _own_ "namespace" (basically, the set of names
that it recognizes). Even though you've imported a name from the
"imported" namespace into your own namespace(*), you don't change
the fact that someFunction() looks in the namespace of the "imported"
module to find the "global".
(*) The form "from module import *" is, by the way, generally a bad
idea, but you can read the archives to find out why as it has
been much discussed in the past.
-Peter
More information about the Python-list
mailing list