Hec Hec - 1 year ago 70
Python Question

How to make dynamic stub functions on the fly?

I have a class with about 200 stub functions, they look something like this:

def name1(self, **kwargs):
return self.run('name-1', kwargs)

def name2(self, ** kwargs):
return self.run('name-2', kwargs)

So on and so forth.

There is a run function that takes care of the real work.

I want to reduce the 200 stub function to just 1 dynamic function that gets called when you make a call to the class with a method name that doesn't exist.

How do I do this?

Answer Source

You can use a __getattr__ method in your class that returns a wrapper function around run. You just need a way to translate between the method name (e.g. name1) and the string that should get passed to the run method (e.g. "name-1"). It would of course be easiest if there wasn't any change. Here's a quick implementation that uses a dictionary for the translation. If you need it to work for many names you might want to do it with string operations and regex instead.

name_translation_dict = {"name1": "name-1", "name2": "name-2"}

def __getattr__(self, name):
    if name not in self.name_translation_dict:
        raise AttributeError()
    translated_name = self.name_translation_dict[name]
    def method(**kwargs):
        return self.run(translated_name, **kwargs)
    return method
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download