Jun 03, 2009 15:32
Often times you need to write wrappers or proxies that are required to support "forwarding functions", i.e. functions that just forward requests to similarly named functions, or do something parametrised by function name. The tedious way to do it is something like this:
class C:
def a(self, arg):
return a + arg
def b(self, arg):
return b + arg
def c(self, arg):
return c + arg
This, however, becomes cumbersome very quickly. Here's a way to generate these functions from a list of function names:
class C:
@staticmethod
def gen_func(name):
return (lambda arg: name + arg)
def __init__(self):
fnames = ['a', 'b', 'c']
for fname in fnames:
self.__dict__[fname] = C.gen_func(fname)
################
# Let's try it out
################
if __name__ == '__main__':
a_c = C()
print a_c.a('a')
print a_c.b('b')
print a_c.c('c')
That's simple, ain't it? You could do more with it, such as make your auto-generated functions accept more than one parameters using *arg (list of positional arguments) or **kwargs(dictionary of named arguments). For some reason, inlining the lambda generation doesn't give the expected results.
Know of a better way to do this? Please do share!
code-generation,
geekdom,
python,
hacking