Inheriting and modifying lots of methods

Steven D'Aprano steven at
Tue Oct 27 21:54:32 CET 2009

On Tue, 27 Oct 2009 10:43:42 -0700, Felipe Ochoa wrote:

> I need to create a subclass from a parent class that has lots of
> methods, and need to decorate all of these. Is there pythonic way of
> doing this other than:
> def myDecorator (meth):
>     @wraps(meth)
>     def newMeth (*args, **kw):
>         print("Changing some arguments here.") return meth(newargs,
>         **kw)
>     return newMeth
> class Parent:
>     def method1(self,args):
>         pass
>     def method2(self,args):
>     # and so on...
>     def methodn(self,args):
>         pass
> class Mine(Parent):
>     for thing in dir(Parent):
>         if type(eval("Parent."+thing)) == type(Parent.method1):
>             eval(thing) = myDecorator(eval("Parent." + thing))
> I'm not even sure that this works! Thanks a lot!

eval() won't work there. exec might, but any time you think you need eval/
exec, you probably don't :)

You can probably do some magic with metaclasses, but the simplest 
solution would be something like this:

class Mine(Parent):

import types
for name in dir(Mine):
    attr = getattr(Mine, name)
    if type(attr) in (types.MethodType, types.UnboundMethodType):
        setattr(Mine, name, myDecorator(attr))

The above (probably) won't touch classmethods and staticmethods. 


More information about the Python-list mailing list