global variable not seen (bug?)

Carl Banks imbosol at vt.edu
Wed Jan 8 14:29:04 EST 2003


Michal Vitecek wrote:
> Mike Meyer wrote:
>>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
> 
> this doesn't help:
> 
> ---session start---
>>>> from imported import *
>>>> GLOBAL_VARIABLE="some value"
>>>> someFunction()
> Traceback (most recent call last):
>  File "<stdin>", line 1, in ?
>  File "imported.py", line 2, in someFunction
>    print GLOBAL_VARIABLE
> NameError: global name 'GLOBAL_VARIABLE' is not defined
>>>> 
> ---session end---
> 
> i must say that this behaviour is pretty strange (non-intuitive at
> least). why is it that the function looks for that variable in the
> scope of its module? wouldn't that be more intuitive if it looked for
> the variable in the current global scope?

They're the same thing, of course.  When you access a global variable
from a function, the current global scope is the module the function
was defined in.

But it seems that you have a different idea of what "current global
scope" means.  You seem to want the following behavior: for the
snippet below, you want the current global scope of the function b to
be module X, because that is the current global scope of b's caller.


module X:

    from Z import b

    def a():
        b()


module Z:

    def b():
        global n
        print n


But, ask yourself this: shouldn't a's current global scope be the
module of a's caller?  You think it's intuitive that b's current
global scope should be the caller, yet it seems you haven't even
thought about what a's current global scope is, but you seem to expect
that a's global scope is the module X, the module where it was
defined.  Am I right?

If that's the case (I won't presume it is, but that's kind of what
happened to me when I made the same mistake), then I would say you
don't exhibit your own idea of what's intuitive!  :-)

The fact is, you've been using the defining global scope of a function
since you've been using modules.  When a and b are defined in the same
module, a calling b, you don't want a to call some other function
depending on where you imported it.  The b that a calls will always be
the object bound to b in a's defining global scope.


The technical term for all this is that Python is lexically scoped.
And it is often believed (including by me) that other scoping
strategies make the code prone to all kinds of name clashes and
unexpected values, and programmers have to work harder to avoid such
errors.


-- 
CARL BANKS




More information about the Python-list mailing list