locals() and globals()
kay.schluehr at gmx.net
Sat Oct 14 18:12:54 CEST 2006
Paolo Pantaleo wrote:
> this exaple:
> def lcl():
> print "n in lcl() is:" +str(n)
> #This will say Name error
> #print new
> print "gobal n is:" +str(n)
> print "new is:" +str(new)
> gobal n is:100
> new is:1
> n in lcl() is:1
> shouldn't be n in lcl() 100 too?
> why accessing the names dictionary globals() and locals() gives
> different results?
Python is statically scoped. The name bindings are fixed at compile
time. Hence you can't achieve dynamic scoping by using the locals()
dictionary and add new names to the locals() which might eventually be
used as local variables in the body of the function. The function still
controls its own state and does not permit delegating state changes via
locals(). That's what objects are for.
More information about the Python-list