Is there a way to change the closure of a python function?

Chris Angelico rosuav at gmail.com
Tue Sep 27 11:01:13 EDT 2016


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.

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



More information about the Python-list mailing list