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

Ian Kelly ian.g.kelly at gmail.com
Tue Sep 27 10:57:19 EDT 2016


On Tue, Sep 27, 2016 at 8:41 AM, jmp <jeanmichel at sequans.com> wrote:
> On 09/27/2016 04:01 PM, Peng Yu 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
>>
>
> If I understood correctly your link:
>
> (untested)
> def func(x):
>     return x+func.y
>
> func.y = 10
> func(5) => 15
> func.y = 100
> func(5) => 105
>
> implements a closure of a function.

That is not a closure. A closure is a construct of lexical scoping.
This is an example of a closure:

def f(x):
    def g():
        return x
    return g

We say that the variables of f are "closed" over the function g. An
example of use:

py> g1 = f(42)
py> g2 = f(64)
py> g1()
42
py> g2()
64

Note that each closure has its own value of x.

The link suggests that object methods in Python are closures because
of the self argument, but I disagree with that; closures are
constructs of lexical scoping.



More information about the Python-list mailing list