Draft Pep (was: Re: Let's Talk About Lambda Functions!)

Daniel Fackrell unlearned at DELETETHIS.learn2think.org
Mon Aug 5 19:16:06 CEST 2002


"Bryan Olson" <fakeaddress at nowhere.org> wrote in message
news:3D4E2E87.9070308 at nowhere.org...
> A full lambda would alleviate the need for the more complex def.


I don't have a strong background with functional languages, but would
something like the following help out?

Python 2.2 (#28, Dec 21 2001, 12:21:22) [MSC 32 bit (Intel)] on win32
Type "copyright", "credits" or "license" for more information.
IDLE 0.8 -- press F1 for help
>>> def strongerLambda(code):
    """A stronger lambda implementation in Python"""
    code = ["    " + line for line in code.split("\n")]
    exec "def tempFunc(*args, **kwargs):\n" + "\n".join(code) + "\n"
    return tempFunc

>>> strongerLambda("x=1\nreturn x")
<function tempFunc at 0x00992560>
>>> strongerLambda("x=1\nreturn x")()
1
>>>

Or, alternately:

>>> def strongerLambda(arglist, code):
    """A stronger lambda implementation in Python"""
    code = ["    " + line for line in code.split("\n")]
    exec "def tempFunc(" + arglist + "):\n" + "\n".join(code) + "\n"
    return tempFunc

>>> strongerLambda("x, y, z", """
    print x
    print y
    print z
    print x+y+z
    return x+y+z
""")
<function tempFunc at 0x009C4BD0>
>>> strongerLambda("x, y, z", """
    print x
    print y
    print z
    return x+y+z
""")(1, 2, 3)
1
2
3
6
>>>

Still not completely anonymous, as it temporarily has a name and that name
shows up later, but it can be used wherever an expression is valid, and
nicely integrates statements such as print, etc. without changing existing
syntax.

Of course, this form requires that you explicitly return any value you want
returned, as opposed to the current lambda.  Trade-offs everywhere, right?

--
Daniel Fackrell (unlearned at learn2think.org)
When we attempt the impossible, we can experience true growth.





More information about the Python-list mailing list