global variable not seen (bug?)

Peter Hansen peter at engcorp.com
Wed Jan 8 16:50:32 EST 2003


Michal Vitecek wrote:
> 
> Peter Hansen wrote:
> >"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".
> 
>  i must say that this behaviour of "global" variables is IHMO pretty
>  uncommon and non-intuitive and i wonder what was the reason the
>  developers chose this way:
>     1) either that global variables have module-only scope

This is definitely the case.  Check the language definition, particularly
this section: http://www.python.org/doc/2.2/ref/execframes.html

>     2) method even though it is imported into different scope still
>     looks for data in module in which it was defined

The method is *not* imported into a different scope.  If you think that,
you still need to learn about "binding" in Python.  The method is defined
in its original scope, which is inside the "imported" module.  You cannot
change that.  What you are doing is creating a *local* name, bound to the
function in the "imported" module (but not affecting it in any way), 
and which just happens to have the same name as that function.  The
function is not changed, and is completely unaware of the fact that you
have created another name bound to it, so it *must* look in its own
module's global namespace for the global name.

In any case, aside from all this non-intuitive (but as a newbie to
a new language, "unexpected" might be a better word for you to use,
since without an understanding of how the language works internally
you probably can't have valid intuitions about it at all), I have
to agree with the other comments which point out "this is definitely
not the right way to do things".

You should be adopting a more modular approach, and you can definitely
do this without any use of global variables.

-Peter




More information about the Python-list mailing list