free variables /cell objects question

Paul Rubin http
Thu Jan 25 13:29:35 CET 2007


"gangesmaster" <tomerfiliba at gmail.com> writes:
> what i see as a bug is this code not working as expected:
> 
> >>> def make_foos(names):
> ...     funcs = []
> ...     for n in names:
> ...             def foo():
> ...                     print "my name is", n
> ...             funcs.append(foo)
> ...     return funcs

But it does work as expected, if your expectations are based on what
closures actually do.

> i have to create yet another closure, make_foo, so that the name
> is correctly bound to the object, rather than the frame's slot:

The Python idiom is:

   def make_foos(names):
       funcs = []
       for n in names:
               def foo(n=n):
                       print "my name is", n
               funcs.append(foo)
       return funcs

The n=n in the "def foo" creates the internal binding that you need.



More information about the Python-list mailing list