Dynamically defined functions via exec in imported module

Nadeem nadeemabdulhamid at gmail.com
Fri Aug 15 23:17:12 EDT 2008


Well, I found one hack that seems to achieve this by accessing the
globals() dictionary of the outermost stack frame and adding an entry
to it for the newly created functions:

import inspect

def dynamicdef(name, amt):
    '''Dynamically defines a new function with the given name that
adds
    the given amt to its argument and returns the result.'''
    stm = "def %s(x):\n\treturn x + %d" % (name, amt)
    print stm
    exec stm in globals()

    ## ADDED THIS TO EXPORT THE NEW FUNCTION NAME TO THE TOP LEVEL...
    inspect.stack()[-1][0].f_globals[name] = eval(name)


I guess I'll go with this unless someone suggests an alternate. Thanks
anyway, :)
--- nadeem



More information about the Python-list mailing list