How do I DRY the following code? class C():
def f1(self, arg1, arg2=None, globals=None, locals=None): ... unique stuff #1 ... ... some common stuff #1 ... ret = eval(args, globals, locals) ... more stuff #2 ... return retval def f2(self, arg1, arg2=None, *args, **kwds): ... unique stuff #2 ... ... some common stuff #1 ... ret = arg1(args, *args, **kwds) ... more common stuff #2 ... return retval def f3(self, arg1, globals=None, locals=None): ... unique stuff #3 ... ... some common stuff #1 ... exec cmd in globals, locals ... more common stuff #2 ... return None def f4(self, arg1, globals=None, locals=None): ... unique stuff #4 ... ... some common stuff #1 ... execfile(args, globals, locals) ... more stuff #2 ... return None f1(...): "Docstring f1" c = C() return c.f1(...) f2(...): "Docstring f2" c = C() return c.f2(...) f3(...): "Docstring f3" c = C() return c.f3(...) Above there are two kinds of duplication: that within class C and that outside which creates an instance of the class C and calls the corresponding method. For the outside duplication, I considered trying: _call_internal = lambda name, *args, **kwds \ c = C() \ fn = getattr(c, name) \ return fn(*args, **kwds) f1 = lambda arg, arg2=None, globals=None, locals=None: _call_internal('f1', ...) f1.__doc__ = """ Docstring f1 """ f2= lambda arg, arg1=None, arg2, *args, **kwds: _call_internal('f2', ...) f2.__doc__ = """ Docstring f2 """ However this strikes me as a little bit cumbersome, and harder understand and maintain than the straightforward duplicated code. Thoughts? Lest the above be too abstract, those who want to look at the full (and redundant) code: http://code.google.com/p/pydbg/source/browse/trunk/api/pydbg/api/debugger.py -- http://mail.python.org/mailman/listinfo/python-list