What are python closures realy like?

2006-12-01 Thread Karl Kofnarson
Hi,
while writing my last program I came upon the problem
of accessing a common local variable by a bunch of 
functions.
I wanted to have a function which would, depending on
some argument, return other functions all having access to
the same variable. An OO approach would do but why not
try out closures...
So here is a simplified example of the idea:
def fun_basket(f):
common_var = [0]
def f1():
print common_var[0]
common_var[0]=1
def f2():
print common_var[0]
common_var[0]=2
if f == 1:
return f1
if f == 2:
return f2
If you call f1 and f2 from the inside of fun_basket, they
behave as expected, so common_var[0] is modified by
whatever function operates on it.
However, calling f1=fun_basket(1); f2 = fun_basket(2) and
then f1(); f2() returns 0 and 0. It is not the way one would
expect closures to work, knowing e.g. Lisp make-counter.
Any ideas what's going on behind the scene?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: What are python closures realy like?

2006-12-02 Thread Karl Kofnarson
> Karl,
> 
> Usually when using this idiom, fun_basket would return a tuple of all of the 
> defined functions, rather than one vs. the other.  So in place of:
>>if f == 1:
>>return f1
>>if f == 2:
>>return f2
> Just do
>>return f1, f2
> (For that matter, the argument f is no longer needed either.)
> 
> Then your caller will get 2 functions, who share a common var.  You don't 
> call fun_basket any more, you've already created your two "closures".  Call 
> fun_basket using something like:
> 
> z1,z2 = fun_basket(None)
> 
> And then call z1() and z2() at your leisure - they should have the desired 
> behavior.
> 
> -- Paul

Thanks a lot Paul and for the other answers. The things are now
clear to me. In fact, in the Lisp example that I mentioned, you
get a list (or let it be association list) of the internal
functions. Then you can call them separately and they work as
you expect but it's due to the fact only that you got them created
at the same time.
-- 
http://mail.python.org/mailman/listinfo/python-list