[Tutor] strange variable problem

Gonçalo Rodrigues op73418 at mail.telepac.pt
Fri May 21 18:06:52 EDT 2004

Em Fri, 21 May 2004 13:32:30 -0700 (PDT), Danny Yoo
<dyoo at hkn.eecs.berkeley.edu> atirou este peixe aos pinguins:

[text snipped]

>So people do run into this enough that it's a FAQ entry.  I get the
>feeling, sometimes, that globals are awkward in Python to discourage their
>use.  *grin*

I think that is only half the story. *grin*

Globals are awkward because scope resolution of names follows some
very *simple* rules: First notice that the scope of a name is
determined at *compile* time - this is important in what follows.

1. If a name is LHS (left-hand-side) of an assignment then it is to be
found in the local scope.

2. Names in an expression are found by going from the local scope,
then the outer scopes (if any), then the global scope then the

The important rule here is number 1. In a situation like

name = 1

def foo(arg):
    name = name + 1

Since name is the LHS of an assignment it is assumed to be in the
local scope. Of course, when *actually running* the code, when
executing the expression name + 1 Python sees that there is no name
bound in the local scope => you get an error. So, by rule 1 you have
to have some way to signal Python's "compiler" (the Translator into
Python bytecode) that name is in the outer scope (in this case the
module-level one). Thus the need for the global declaration.

If you want to preserve the simplicity of rule 1 (and I for one will
shoot down everyone who wants to break it :-) you *must* have some
special notation to allow *rebinding* of names in outer scopes.
Currently rebinding is only allowed in the global scope not in other
outer scopes (as defined by functions) but it seems that Guido wants
to introduce it except that no good notation has yet been found. I for
one favour a new assignment operator, say :=, instead of a declaration
like global.

With my best regards,
G. Rodrigues

More information about the Tutor mailing list