0

I want to inherit from class just to add decorators to its methods.

Is there a shortcut to do this without redefining each base class method?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
a bsss
  • 25
  • 4
  • You could intercept *all* attribute access via `__getattribute__`, then apply the same function directly there rather than as a decorator. – jonrsharpe May 16 '18 at 09:00

2 Answers2

0

Sure, you can do this dynamically. Suppose you have some class:

>>> class Foo:
...    def bar(self): print('bar')
...    def baz(self): print('baz')
...

And a decorator:

>>> def deco(f):
...    def wrapper(self):
...       print('decorated')
...       return f(self)
...    return wrapper
...

Then simply inherit:

>>> class Foo2(Foo):
...     pass
...

Then loop over your original class, and apply the decorator to your new child-class:

>>> for name, attr in vars(Foo).items():
...     if callable(attr):
...         setattr(Foo2, name, deco(attr))
...

So...

>>> x = Foo2()
>>> x.bar()
decorated
bar
>>> x.baz()
decorated
baz

Now, using if callable(attr) might not be restrictive enough. You might want to ignore "dunder" methods, so instead:

for name, attr in vars(Foo):
    if callable(attr) and not name.startswith('__'):
        setattr(Foo2, name, attr)

might be more appropriate. Depends on your use-case.

And just for fun, here we can also use the type constructor:

In [17]: class Foo:
    ...:     def bar(self): print('bar')
    ...:     def baz(self): print('baz')
    ...:

In [18]: def deco(f):
    ...:     def wrapper(self):
    ...:         print('decorated')
    ...:         return f(self)
    ...:     return wrapper
    ...:

In [19]: Foo3 = type(
    ...:     'Foo3',
    ...:     (Foo,),
    ...:     {name:deco(attr) for name, attr in vars(Foo).items() if callable(attr)}
    ...: )

In [20]: y = Foo3()

In [21]: y.bar()
decorated
bar

In [22]: y.baz()
decorated
baz
juanpa.arrivillaga
  • 88,713
  • 10
  • 131
  • 172
0

You can use a class decorator to encapsulate the whole work

Example code:

def deco(func):
    """Function decorator"""
    def inner(*args, **kwargs):
        print("decorated version")
        return func(*args, **kwargs)
    return inner

def decoclass(decorator):
    """Class decorator: decorates public methods with decorator"""
    def outer(cls):
        class inner(cls):
            pass
        for name in dir(cls):
            if not name.startswith("_"):     # ignore hidden and private members
                # print("decorating", name)  # uncomment for tests
                attr = getattr(inner, name)
                setattr(inner, name, decorator(attr))
        return inner
    return outer

class Foo:
    """Sample class""
    def foo(self):
        return "foo in Foo"

You can then use it:

>>> @decoclass(deco)
class Foo2(Foo):
    pass

>>> f = Foo2()
>>> f.foo()
decorated version
'foo in Foo'
Serge Ballesta
  • 143,923
  • 11
  • 122
  • 252