Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python dynamic function creation with custom names

Apologies if this question has already been raised and answered. What I need to do is very simple in concept, but unfortunately I have not been able to find an answer for it online.

I need to create dynamic functions in Python (Python2.7) with custom names at runtime. The body of each function also needs to be constructed at runtime but it is (almost) the same for all functions.

I start off with a list of names.

func_names = ["func1", "func2", "func3"] 

Note that the func_name list can hold a list of arbitrary names, so the names will NOT simply be func1, func2, func3, ....

I want the outcome to be :

    def func1(*args):         ...      def func2(*args):         ...      def func3(*args):         ... 

The reason I need to do this is that each function name corresponds to a test case which is then called from the outside world.

update: There is no user input. I'm tying two ends of a much bigger module. One end determines what the test cases are and among other things, populates a list of the test cases' names. The other end is the functions themselves, which must have 1:1 mapping with the name of the test case. So I have the name of the test cases, I know what I want to do with each test case, I just need to create the functions that have the name of the test cases. Since the name of the test cases are determined at runtime, the function creation based on those test cases must be at runtime as well.

update: I can also wrap this custom named functions in a class if that would make things easier.

I can hard-code the content of the functions (since they are almost the same) in a string, or I can base it off of a base class previously defined. Just need to know how to populate the functions with this content.

For example:

    func_content = """                    for arg in args:                        print arg                    """ 

Thanks in advance,

Mahdi

like image 759
mahdiolfat Avatar asked Nov 01 '12 19:11

mahdiolfat


People also ask

How do you create a dynamic function in Python?

Python Code can be dynamically imported and classes can be dynamically created at run-time. Classes can be dynamically created using the type() function in Python. The type() function is used to return the type of the object. The above syntax returns the type of object.

How do you create a dynamic variable name in Python?

Use the for Loop to Create a Dynamic Variable Name in Python Along with the for loop, the globals() function will also be used in this method. The globals() method in Python provides the output as a dictionary of the current global symbol table.

How do you call a function dynamically in Python?

To do this in Python you have to access the global namespace. Python makes you do this explicitly where PHP is implicit. In this example we use the globals() function to access the global namespace. globals() returns a dictionary that includes area as a key and the value is a reference to the area() function.

How do you change the name of a function in Python?

The only way to rename a function is to change the code .


2 Answers

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> 
like image 75
Shane Holloway Avatar answered Sep 22 '22 09:09

Shane Holloway


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):     pass  def make_method(name):     def _method(self):         print("method {0} in {1}".format(name, self))     return _method  for 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> 
like image 21
Paul Whipp Avatar answered Sep 25 '22 09:09

Paul Whipp