[BangPypers] Enclosing lexical context
Anand Chitipothu
anandology at gmail.com
Thu Apr 15 20:03:04 CEST 2010
2010/4/15 Picachu Nioto <picachu.nioto at gmail.com>:
> Could some one explain to me this sentence, I read in an example online
>
> "Python doesn't implement assignment of variables bound in an enclosing
> lexical context"
>
> Example,
> a=[b]
Consider the following example:
a = 1
def f():
b = 2
def g():
c = 3
# this function can access all a, b and c variables.
print a, b, c
# c can be reassigned
c = 42
# a can be reassigned only if it is declared as global,
otherwise it is considered as local to this function
global a
a = 42
# b can't be reassigned because it is neither local nor global.
It is in the enclosing lexical context
SInce b can't be reassigned, the work-around is to modify the object
instead of reassigning.
However, python3.0 added a new "nonlocal" construct to enable that.
With python 3, you should be able to say:
nonlocal b
b = 42
Anand
More information about the BangPypers
mailing list