Alex Rivera | Logout

How to dynamically create module level functions from methods in a class

Asked 2010-09-08T02:45:40.707
9

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

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 
Edit
Report

1 Answer

1

actually your code is right but when return func(*args, **kwargs) executes, args will pass empty tuple like () and there are no parameters in your method2, so it raises such exception,

a quick solution towards your problem would be, like

class TestClass(object):
    def __init__(self):
        pass

    def method1(self, arg1):
        print 'method 1 %s' % arg1

    def method2(self, *args, **kw):
        print 'method 2'
answered 2010-09-08T03:04:26.090

Your Answer