Creating anonymous functions using eval

Julian Smith jules at REMOVETHIS.op59.net
Tue Jul 12 07:02:18 EDT 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()
        return foo

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
            return y
        '''))

- which outputs:

    x^2 + y^2 =  29
    5


You can also mimic conventional function definitions:

    f = fn( '''
        ( x, y):
            print 'x, y=', x, y
            print 1.0*x/y
            return y
        ''')

    print 'calling f'
    f( 5, 6)

This outputs:

    calling f
    x, y= 5 6
    0.833333333333


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
python's lambda.

But... I haven't seen this technique mentioned anywhere, so does anyone know
of any problems that I should be wary of?

- Julian

-- 
http://www.op59.net/



More information about the Python-list mailing list