Functions as Objects, and persisting values
Rich Harkins
rich at worldsinfinite.com
Mon Nov 5 15:09:39 EST 2007
[snip]
> The "thing" you observe here is a called a closure. It consists of the
> local variables surrounding e. So as long as you keep a reference to e,
> you keep one to the variables of d itself.
>
> Diez
More specifically though it keeps references to the requested variables
only:
def closed():
x = global_x
y = "Y_VAR"
def inner():
return y
return inner
class Destroyable(object):
def __del__(self):
print "DESTROYED"
global_x = Destroyable()
inner = closed()
print inner()
del global_x
print inner()
print "HERE"
You will get:
Y_VAR
DESTROYED
Y_VAR
HERE
If the entire dict of closed() was kept you would have seen:
Y_VAR
Y_VAR
HERE
DESTROYED
Since closed hadn't been destroyed yet: thus there was only one
reference remaining to global_x after closed() and inner() were called.
Rich
More information about the Python-list
mailing list