What are python closures realy like?

Felipe Almeida Lessa felipe.lessa at gmail.com
Fri Dec 1 16:53:03 EST 2006


On 12/1/06, Karl Kofnarson <kofnarson at gmail.com> wrote:
[snip]
> 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

Everytime you call fun_basket you create another common_var.

> However, calling f1=fun_basket(1); f2 = fun_basket(2) and
> then f1(); f2() returns 0 and 0.

Two calls to fun_basket, two different common_var's, two f1's and two
f2's. Each f1/f2 pair have access to a different common_var, so it's
working as expected. To work as you expected, fun_basket should be on
the same block common_var is defined.

-- 
Felipe.



More information about the Python-list mailing list