I have recently been working on an object-oriented wrapper for the Python bindings to my [libxtract][1] feature extraction library. I used SWIG to auto-generate the bindings, and SWIG generally does a great job. The problem is that the functions it generates follow the original C code quite precisely, and aren’t very ‘Pythonic’. I wanted to create a nice Python class to hide some of the nastiness of the auto-generated functions, but became slightly daunted by having to hand-code every method of the new Xtract class with 50 very similar methods! Instead I decided to take advantage of Python’s support for [lexical closures][2] to auto-generate the methods from the libxtract function descriptors using a method factory. The concept works like this (I think this is a fairly common idiom in Python):
#!/usr/bin/python
class foo:
'''Dummy class'''
def __init__(self):
for y in range(3):
doc = "Returns the sum of a number and %.2f" % y
name = 'add%d' % y
adder = self.adder_factory(y)
setattr(self, name, adder)
# Set the docstring
self.__dict__[name].__doc__ = doc
@staticmethod
def adder_factory(y):
"Method for generating adder functions using a lexical closure"
def adder(x):
return x + y
return adder
a = foo()
x = 3
print a.add0(x) # prints 3
print a.add1(x) # prints 4
print a.add2(x) # prints 5