What are python closures realy like?

Carl Banks pavlovevidence at gmail.com
Fri Dec 1 18:44:40 EST 2006


Karl Kofnarson wrote:
> 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.


Lisp works the same way.

* (defun fun_basket (f)
        (let ((common_var 0))
                (defun f1 ()
                        (print common_var)
                        (setf common_var 1))
                (defun f2 ()
                        (print common_var)
                        (setf common_var 2))
                (if (eq f 1)
                        #'f1
                        #'f2)))

FUN_BASKET
* (setf (symbol-function 'f1a) (fun_basket 1))

; Converted F1.
; Converted F2.

#<Interpreted Function F1 {5807C9A1}>
* (setf (symbol-function 'f2a) (fun_basket 2))

#<Interpreted Function F2 {5807D409}>
* (f1a)

0
1
* (f2a)

0
2



> Any ideas what's going on behind the scene?

Every time you call the function, a new closure is created.


Carl Banks




More information about the Python-list mailing list