Confusion re "global" statement

Steven Taschuk staschuk at telusplanet.net
Sun Aug 31 16:03:17 EDT 2003


Quoth Chris Stromberger:
  [...]
> Can someone explain?  I guess it has to do with the fact that I'm not
> reassigning the name d in the function, but it seems counter-intuitive
> that I'm able to modify a global inside the function w/o saying
> "global d".

Strictly speaking you're not modifying a global -- you're
modifying a dict which a global name happens to be bound to.

In detail:

There's the name 'd' and the dict to which that name is bound.  It
is the name which is global; the dict just is.  For example,
    d = {}
    def foo(x):
        x[3] = 4
    foo(d)
During the call to foo() here, x is bound to the same object as d;
x is a local name, and d a global one.  It is not meaningful to
ask whether the dict to which they are both bound is local or
global; the concept doesn't apply.

So, since
    d[key] = value
modifies the dict (adding an element to it) but does not modify
the name d (which continues to refer to that dict), strictly
speaking this code does not modify a global.  The global statement
is only needed when you are modifying a global in the strict sense
-- as you said, when reassigning d.

(Note that it would be practically impossible to require a global
statement when merely modifying an object by way of a global
variable, since the compiler can't determine whether statements
such as
    d.some_random_method()
    some_random_function(d)
modify the object known as d.  The best the compiler could do is
to require a global statement for *any* use of a global name; but
this would be unbearably unwieldly, since you'd have to use a
global statement to refer to other functions defined in the
module, to modules imported in module scope, etc..)

(Well, a different language might be able to infer mutation
statically... anybody know of work in this area?)

-- 
Steven Taschuk                staschuk at telusplanet.net
"I tried to be pleasant and accommodating, but my head
 began to hurt from his banality."   -- _Seven_ (1996)





More information about the Python-list mailing list