What are python closures realy like?
Fredrik Lundh
fredrik at pythonware.com
Wed Dec 6 04:54:02 EST 2006
"Paddy" wrote:
> I played around a bit. The following is a 'borg' version in that there
> is only one counter shared between all calls of the outer function:
>
>>>> def fun_borg_var(initial_val=0):
> ... def borg_var_inc(x=1):
> ... fun_borg_var._n += x
a drawback with the function attribute approach compared to a real closure
is that the function is no longer a self-contained callable:
def fun_borg_var(initial_val=0):
def borg_var_inc(x=1):
fun_borg_var._n += x
return fun_borg_var._n
def borg_var_dec(x=1):
fun_borg_var._n -= x
return fun_borg_var._n
try:
fun_borg_var._n = fun_borg_var._n
except:
fun_borg_var._n = initial_val
return (borg_var_inc, borg_var_dec)
up1, dn1 = fun_borg_var()
del fun_borg_var # won't need this any more
print up1() # oops!
so you might as well use a good old global variable, and initialize it as
usual.
</F>
More information about the Python-list
mailing list