Creating anonymous functions using eval
jules at REMOVETHIS.op59.net
Tue Jul 12 13:02:18 CEST 2005
I've been playing with a function that creates an anonymous function by
compiling a string parameter, and it seems to work pretty well:
def fn( text):
exec 'def foo' + text.strip()
This can be used like:
def foo( x):
print x( 2, 5)
foo( fn( '''
( x, y):
print 'x^2 + y^2 = ', x*x + y*y
- which outputs:
x^2 + y^2 = 29
You can also mimic conventional function definitions:
f = fn( '''
( x, y):
print 'x, y=', x, y
print 'calling f'
f( 5, 6)
x, y= 5 6
You do things like allow/require an initial `def' for clarity, check that all
the lines of text are indented so that nothing is executed when the anonymous
function is created, etc etc.
Obvious disadvantages are that the function text may have to escape quotes,
and will not be showed with syntax colouring in editors.
Apart from that, it seems quite a useful way of overcoming the limitations of
But... I haven't seen this technique mentioned anywhere, so does anyone know
of any problems that I should be wary of?
More information about the Python-list