Closure in python? -
when run code, result:
15 15 i expect output should be
15 17 but not. question is: why?
def make_adder_and_setter(x): def setter(n): x = n return (lambda y: x + y, setter) myadder, mysetter = make_adder_and_setter(5) print myadder(10) mysetter(7) print myadder(10)
python 2.x has syntax limitation doesn't allow capture variable in read/write.
the reason if variable assigned in function there 2 possibilities:
- the variable global , has been declared
global x - the variable local of function
more it's ruled out variable local of enclosing function scope
this has been superseded in python 3.x addition of nonlocal declaration. code work expected in python 3 changing to
def make_adder_and_setter(x): def setter(n): nonlocal x x = n return (lambda y: x + y, setter) the python 2.x runtime able handle read-write closed on variable @ bytecode level, limitation in syntax compiler accepts.
you can see lisp compiler generates python bytecode directly creates adder closure read-write captured state at end of video. compiler can generate bytecode python 2.x, python 3.x or pypy.
if need closed-over mutable state in python 2.x trick use list:
def make_adder_and_setter(x): x = [x] def setter(n): x[0] = n return (lambda y: x[0] + y, setter)
Comments
Post a Comment