Assignments and globals

Alex Martelli alex at magenta.com
Fri Aug 18 03:53:33 EDT 2000


<echuck3 at my-deja.com> wrote in message news:8ni51o$csn$1 at nnrp1.deja.com...
> Here's a very distilled version of my problem:
>
> settings = { 'x': {},  'y': {} }
> class K:
>     def foo(self):
>         settings = settings['x']
> K().foo()
>
> I get "Name error: settings" on this. If I change the line to:
>         s = settings['x']
>
> Then everything works. It appears that in the statement 'a = b', Python
> starts mucking with the namespace before b is evaluated.
>
> Is there a good reason for this? Is it even a design point, or an
> accident of implementation? I wonder if JPython has this problem.

Whether it's a "problem" or not, any version of Python will have
it just as much, because it's a fundamental part of the language's
design.  Basically, when any function (or method) is compiled, the
Python compiler must figure out, for each name the function uses,
whether it's a local or global one.  It uses the following rules:
a. if an explicit statement:
        global name
   appears in the function, then the name is global
b. else, if the name is bound in the function, i.e.
        name = anyexpression
   appears in the function, then the name is local
c. else, the name is global.

The name is taken as either global or local uniformly throughout
the function: not as local in some parts of it, and global in other
parts.

So: if you want your K.foo method to re-bind the global settings
variable, add a statement
        global setting
at the start of your K.foo method.  If you want K.foo to READ the
global settings variable, but not re-bind it, use something other
than 'settings' on the left of the equal-sign in the assignment
statement[s] in the method.

It seems to me that these rules are quite simple, once learned:
they let you perform basically whatever you need to, and, in fact,
they let you do so without too much trouble.  Thus, I, personally,
do not see this as "a problem" at all.


Alex






More information about the Python-list mailing list