I’m looking for a ‘simple’ solution to override systematically some inherited methods in Python (=>2.6). Based on my previous question here, I’ll come up a solution:
def override(cls, o):
"""Override class method(s)."""
for t in o: # possible problem; nondeterministic order
for name in o[t]:
mtbo= getattr(cls, name).im_func
om= t(mtbo)
om.__name__= mtbo.__name__
om.__doc__= mtbo.__doc__
# What additional magic is needed here to act as 'genuine' method of super class?
setattr(cls, name, om)
if __name__== '__main__':
class B(object):
def f1(self, val):
"""Doc of B.f1"""; print '1: ', val
def f2(self, val):
"""Doc of B.f2"""; print '2: ', val
class A(B):
pass
def t(f, msg):
def g(self, *args, **kwargs):
print msg, ' entering'; result= f(self, *args, **kwargs)
return g
t1= lambda f: t(f, 't1'); t2= lambda f: t(f, 't2')
override(A, {t1: ['f1', 'f2'], t2: ['f2']})
def tst(c):
c.f1(1); print c.f1.__name__, c.f1.__doc__
c.f2(2); print c.f2.__name__, c.f2.__doc__
tst(B()), tst(A())
This seems to work well enough for my (current) purposes. However I like to be able to override as transparent as possible, therefore I’ll preserve the super class methods name and doc. Now my specific question is: should I preserve anything else? What is your solution for this?
Update:
I think now this questions has much wider ramifications: I quess I should have asked (originally) how to decorate methods, or functions reasonable enough pythonic way.
Instead of manually assigning
__name__,__doc__, and possibly others, you can likely just callfunctools.update_wrapperto ensure the relevant attributes are copied.