There is a class with the following structure:
class MyClass1:
def verb_function(self, verb, *args, **kwargs):
return do_something(verb, *args, **kwargs)
def verba(self, *args, **kwargs):
return self.verb_function('verba', *args, **kwargs)
def verbb(self, *args, **kwargs):
return self.verb_function('verbb', *args, **kwargs)
def verbc(self, *args, **kwargs):
return self.verb_function('verbc', *args, **kwargs)
So we have many functions that all do essentially the same thing with different command verbs.
My use case is calling a CLI excutable with more than 60 possible verbs.
This means the current implementation contains a long passage of repeating code that defines all the method functions for the verbs.
Is there a more compact way to express this in Python?
I was thinking about something like this:
class MyClass2:
verbs = ['verba', 'verbb', 'verbc']
def verb_function(self, verb, *args, **kwargs):
return do_something(verb, *args, **kwargs)
for verb in MyClass2.verbs:
setattr(MyClass2, verb, MyClass2.verb_function)
Obviously this code doesn’t work.
I think we’d need something more complicated instead of this simple setattr()
call.
Maybe this can be done with functions from the inspect
module and/or decorators?
I played around with this, but the closest I got was that I was able to call verb_function
by the other names, but it didn’t know that it was called by this name (eg. inspect.currentframe().f_code.co_name
always returned "verb_function"
instead of "verba"
).
Is there a standard approach to this kind of problem that I didn’t find?