What are python closures realy like?

Karl Kofnarson kofnarson at gmail.com
Sat Dec 2 03:23:58 EST 2006


> 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.



More information about the Python-list mailing list