Securing a future for anonymous functions in Python

Paul L. Du Bois polytope at gmail.com
Thu Dec 30 17:01:34 EST 2004


Jp Calderone wrote:
>   I'm not saying "boo hoo lambdas are crippled fix them waah".  I'm
saying
> "Lambdas and generator comprehensions are not comparable in this
sense and
> arguments based on one should not be used to support positions about
the
> other".

This post and Michael Spencer's post which proposed (expr for args(a,
*b, **c)) got me wondering whether this could be done already today.
My solution is unfortuantely implementation-specific.  I can't find a
way for a generator (let alone a generator expression) to refer to
itself; neither do generators have writable attributes.  With those
features, one can imagine a more portable (and more verbose) solution.

I find that I don't really like the generator-like syntax.  To me, it
makes sense for an unnamed function to look like a named function
without a name, eg:

callbacks['foo'] = def (a,b): ... expr or statement? ...

It seems to work in Lua (not that I'm a big fan of Lua).  Thus, I'm not
sure what my point is with this code; maybe just that there are
workarounds if lambda ceases to exist.  Also, with this sort of
solution, nobody can complain that genexps/listcomps/"lambdas" get
preferential treatment <wink>

Anyway, this is tested in Win32 python 2.4.  It adds a function "fn"
(name stolen from Arc) which turns a specially-written generator
expression into an anonymous function.  Default args, *args, *kwargs
are all unsupported.  I'm sorry if google groups eats my leading
whitespace; I've one-lined things to reduce the effect.

def fn(gen):
"""Turns a generator expression into a callable."""
def anonymous(*args): return gen.next()
return anonymous

def args():
"""Works with fn(); yields args passed to anonymous()."""
while True: yield sys._getframe(2).f_locals['args']

args = args()

foo = fn(a + b * c for (a,b,c) in args)
assert foo(3,4,5) == 3+4*5
assert foo(4,5,6) == 4+5*6




More information about the Python-list mailing list