[Tutor] Notes on namespaces, scopes, etc

Kent Johnson kent37 at tds.net
Thu Jul 27 18:46:44 CEST 2006


Dave Kuhlman wrote:
> I've written up a few notes on Python namespaces and scopes.  If
> anyone has corrections, comments, or suggestions, I'd appreciate
> them. You can find my comments here:
>
>     http://www.rexx.com/~dkuhlman/python_comments.html#namespaces

You wrote, "If a variable is assigned a value /anywhere/ in a scope 
(...), then that variable is local to that scope. Otherwise, the 
variable is global."

You omit the enclosing scope and the builtin namespace. A variable can 
be defined in
- local scope
- any of zero or more enclosing scopes
- global scope
- builtin namespace

Names are also bound by for statements and except clauses.

You might note that augmented assignment (e.g. a += 1) counts as 
assignment in the local scope. This is a common cause of UnboundLocalError:

In [5]: a=1

In [6]: def foo():
   ...:     a+=1
   ...:
   ...:

In [7]: foo()
---------------------------------------------------------------------------
exceptions.UnboundLocalError                         Traceback (most 
recent call last)

D:\Projects\e3po\<ipython console>

D:\Projects\e3po\<ipython console> in foo()

UnboundLocalError: local variable 'a' referenced before assignment


I think modifying globals() is guaranteed to work. Modifying locals() 
only works at global scope, i.e. when locals() is globals().

You wrote, "Note that for lexically/statically nested scopes (for 
example, a function defined inside a function), it seems that globals() 
and locals() still give access to all items in the accessible 
namespaces." I'm not sure what you mean by this. locals() doesn't give 
access to items in nested scopes:

In [1]: x=1

In [2]: def maker():
   ...:     y=2
   ...:     def showLocals():
   ...:         z=3
   ...:         print locals()
   ...:     return showLocals
   ...:

In [3]: sl=maker()

In [4]: sl()
{'z': 3}

See also
http://docs.python.org/ref/naming.html

Kent




More information about the Tutor mailing list