functional programming and default parameters
Tim Peters
tim.one at home.com
Fri Jun 29 04:04:08 EDT 2001
[Nick Perkins, tries assorted ways to make a list of functions s.t.
> fns[0]() -> 0
> fns[1]() -> 1
> fns[2]() -> 2
> etc.
but without abusing default arguments]
Here's one easy way:
>>> from __future__ import nested_scopes
>>> def makefunc(i):
... return lambda: i
>>> fns = [makefunc(i) for i in range(10)]
>>> fns[5]()
5
>>> fns[2]()
2
>>>
etc. Without nested scopes, you may have to resort to eval (or exec in
fancier contexts):
>>> fns = [eval("lambda: %d" % i) for i in range(10)]
>>> fns[5]()
5
>>> fns[2]()
2
>>
etc.
More information about the Python-list
mailing list