Python dynamic function creation with custom names

For what you describe, I don’t think you need to descend into eval or macros — creating function instances by closure should work just fine. Example:

def bindFunction1(name):
    def func1(*args):
        for arg in args:
            print arg
        return 42 # ...
    func1.__name__ = name
    return func1

def bindFunction2(name):
    def func2(*args):
        for arg in args:
            print arg
        return 2142 # ...
    func2.__name__ = name
    return func2

However, you will likely want to add those functions by name to some scope so that you can access them by name.

>>> print bindFunction1('neat')
<function neat at 0x00000000629099E8>
>>> print bindFunction2('keen')
<function keen at 0x0000000072C93DD8>

Leave a Comment