functional programming and default parameters

Nick Perkins nperkins7 at
Fri Jun 29 08:52:54 CEST 2001

Here is an experiment with functional programming and default parameters..
(the example uses trivial functions, but it's the principle of the thing...)

..suppose i want to create a list of functions with no parameters,
such that:

fns[0]() -> 0
fns[1]() -> 1
fns[2]() -> 2

this does not work:

>>> fns = [lambda:i for i in range(3)]
>>> fns[0]()
>>> fns[1]()

but this does work:

>>> fns = [lambda i=i:i for i in range(3)]
>>> fns[0]()
>>> fns[1]()

..but the problem is that i wanted functions of zero parameters,
not functions with one optional parameter:

>>> fns[1](99)
( oops! not intended to be used this way! )

Nested scopes do not seem to solve the problem,
I have tried things like:

from __future__ import nested_scopes
def fnlist(n):
    list =[]
    for i in range(n):
        def fn():       #or: def fn(i=i)
            return i
    return list

.. but the result is the same:
the inner function needs to have i as a default parameter
in order to 'freeze' the value of i into the function,
thereby also producing functions with one optional parameter.

Can this be done without using default parameters?

More information about the Python-list mailing list