Securing a future for anonymous functions in Python
Alex Martelli
aleaxit at yahoo.com
Fri Dec 31 12:38:24 EST 2004
Paul L. Du Bois <polytope at gmail.com> wrote:
...
> are all unsupported. I'm sorry if google groups eats my leading
> whitespace; I've one-lined things to reduce the effect.
It does/did, so let me repost while fixing it since this is truly,
deliciously evil:
> 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
Paul, you really SHOULD have posted this BEFORE I had to send in the
files for the 2nd ed's Coobook... this gets my vote for the most
delightful abuse of sys._getframe even (and I've seen quite a few;-).
Kudos!!!
Alex
More information about the Python-list
mailing list