Is there a way to change the closure of a python function?
Jussi Piitulainen
jussi.piitulainen at helsinki.fi
Wed Sep 28 00:16:44 EDT 2016
Chris Angelico writes:
> On Wed, Sep 28, 2016 at 7:19 AM, Terry Reedy wrote:
>> The value of the cell variable is writable from within the body of the
>> closure function if declared nonlocal, but not otherwise, and not from
>> without. The latter may be what Peng meant by 'change' and the blogger by
>> 'read-only'.
>>
>
> Not from entirely without, but it's possible for two functions to
> share a cell. I don't know the mechanics of how nonlocal assignment
> works, but ultimately, it's updating the cell that both closures see,
> so it's going to affect the other function too.
Standard example:
def make():
def inquire():
return balance
def deposit(amount):
nonlocal balance
balance += amount
def withdraw(amount):
nonlocal balance
balance -= amount
balance = 0
return inquire, deposit, withdraw
inq1, put1, get1 = make()
inq2, put2, get2 = make()
put1(30) ; get1(10) ; put1(40)
put2(500) ; put2(500) ; put2(500)
assert inq1() == 60
assert inq2() == 1500
More information about the Python-list
mailing list