Is there a way to change the closure of a python function?
Peng Yu
pengyu.ut at gmail.com
Tue Sep 27 22:49:31 EDT 2016
On Tue, Sep 27, 2016 at 10:01 AM, Chris Angelico <rosuav at gmail.com> wrote:
> On Wed, Sep 28, 2016 at 12:01 AM, Peng Yu <pengyu.ut at gmail.com> wrote:
>> Hi, In many other functional language, one can change the closure of a
>> function. Is it possible in python?
>>
>> http://ynniv.com/blog/2007/08/closures-in-python.html
>>
>
> From the blog post:
>
> """In some languages, the variable bindings contained in a closure
> behave just like any other variables. Alas, in python they are
> read-only."""
>
> This is not true, at least as of Python 3.
So in Python 2, this is true?
> def makeInc(x):
> def inc(y, moreinc=0):
> # x is "closed" in the definition of inc
> nonlocal x
> x += moreinc
> return y + x
> return inc
>
> The 'nonlocal' keyword is like 'global', applying only to assignments
> (the blog post already mentions the possibility of mutating an object
> rather than reassigning it), and permitting assignment into a broader
> scope than the function's locals. You can also have multiple closures
> in the same context, and changes made by one of them will affect the
> others.
>
> ChrisA
> --
> https://mail.python.org/mailman/listinfo/python-list
--
Regards,
Peng
More information about the Python-list
mailing list