I am trying to dynamically create module level functions from the methods in a class. So for every method in a class, I want to create a function with the same name which creates an instance of the class and then calls the method.
The reason I want to do this is so I can take an object-oriented approach to creating Fabric files. Since Fabric will call module level functions but not methods of a class, this is my work-around.
I have used the following links to get me started
- How do I get list of methods in a Python class?
- dynamically adding functions to a Python module
- How do I call setattr() on the current module?
- The Python getattr Function
- Calling a function of a module by using its name (a string)
- How to modify the local namespace in python
And I have come up with the following code
import inspect
import sys
import types
class TestClass(object):
def __init__(self):
pass
def method1(self, arg1):
print 'method 1 %s' % arg1
def method2(self):
print 'method 2'
def fabric_class_to_function_magic(module_name):
# get the module as an object
print module_name
module_obj = sys.modules[module_name]
print dir(module_obj)
# Iterate over the methods of the class