What are python closures realy like?

Paul McGuire ptmcg at austin.rr._bogus_.com
Fri Dec 1 18:20:01 EST 2006


"Karl Kofnarson" <kofnarson at gmail.com> wrote in message 
news:pan.2006.12.01.21.33.44.518447 at gmail.com...
> 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

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 





More information about the Python-list mailing list