Confused about nested scopes and when names get added to namespaces

Aahz aahz at pythoncraft.com
Wed Sep 8 18:45:29 EDT 2010


In article <d020e332-f2f2-4a82-ae1b-2ae071211b33 at n3g2000yqb.googlegroups.com>,
Russell Warren  <russandheather at gmail.com> wrote:
>
>def test4():
>    print "running test4..."
>    x = 1
>    def innerFunc():
>        print "inner locals():",
>        print "%s" % locals()  # how is x in locals in this case??
>        print x
>        x = 2  #ONLY ADDED LINE TO TEST3
>    innerFunc()
>    print "x left as %s\n" % x
>
>In this case I get "UnboundLocalError: local variable 'x' referenced
>before assignment".  I think this means that the compiler (prior to
>runtime) inspected the code, determined I will do an assignment,
>decided _not_ to bring the parent's x into the local namespace, and as
>a result caused the unbound name problem at runtime.

Bingo!

>It seems that the parent's "x" is brought directly into the local
>namespace (when appropriate), rather than the namespace lookup just
>moving up the hierarchy when not found.  This is confusing to me and
>is making me question my understanding of namespace lookups.  Are
>nested scopes a special case where the lookup is handled differently?
>
>What if I want to change the value of the parent's "x"?  test4 implies
>that I can't.

You need Python 3.x and the "nonlocal" keyword.
-- 
Aahz (aahz at pythoncraft.com)           <*>         http://www.pythoncraft.com/

[on old computer technologies and programmers]  "Fancy tail fins on a
brand new '59 Cadillac didn't mean throwing out a whole generation of
mechanics who started with model As."  --Andrew Dalke



More information about the Python-list mailing list