Python dynamic function creation with custom names Python dynamic function creation with custom names python python

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 func1def 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>


Extending on Shane's answer since I just found this question when looking for a solution to a similar problem. Take care with the scope of the variables. You can avoid scope problems by using a generator function to define the scope. Here is an example that defines methods on a class:

class A(object):    passdef make_method(name):    def _method(self):        print("method {0} in {1}".format(name, self))    return _methodfor name in ('one', 'two', 'three'):    _method = make_method(name)    setattr(A, name, _method)

In use:

In [4]: o = A()In [5]: o.one()method one in <__main__.A object at 0x1c0ac90>In [6]: o1 = A()In [7]: o1.one()method one in <__main__.A object at 0x1c0ad10>In [8]: o.two()method two in <__main__.A object at 0x1c0ac90>In [9]: o1.two()method two in <__main__.A object at 0x1c0ad10>


There probably is a sort of introspection to do this kind of thing, but I don't think it would be the pythonic approach to the problem.

I think you should take advantage of the nature of functions in python as first level citizens. Use closures as Shane Holloway pointed, to customize the function contents as you like. Then for the dynamic name binding, use a dictionary whose keys are the names defined dynamically, and the values will be the functions itself.

def function_builder(args):    def function(more_args):       #do stuff based on the values of args    return functionmy_dynamic_functions = {}my_dynamic_functions[dynamic_name] = function_builder(some_dynamic_args)#then use it somewhere elsemy_dynamic_functions[dynamic_name](the_args)

Hope it makes sense to your use case.