1

I'm wondering if it's possible to have a class which automatically wraps all of its methods, without it being necessary to explicity decorate each of them.

For example, instead of doing this:

class MyClass:
    @mydecorator
    def mymethod1(...):
        ...

    @mydecorator
    def mymethod2(...):
        ...

I'd like to do something like this:

class MyClass(metaclass=DecoratedMethods):
    def mymethod1(...):
        ...

    def mymethod2(...):
        ...

Here I'm hinting at metaclasses, but I'm not sure it's the right solution path. I've just discovered the __prepare__ protocol. This would allow me to do something naive like decorate all functions or all callables in the class namespace, but that's not really what I want. I only want to decorate methods(class methods and instance methods).

Python has so many metaprogramming facilities, I'd be surprised if there wasn't a way... Or at least a better way than decorating each method manually?

I'm using python 3.6.

Thanks!

Charles Langlois
  • 4,198
  • 4
  • 16
  • 25
  • 1
    This might be a duplicate. The existing answers points out that using _metaclass_ or a _class_decorator_ are solutions for that. Probably equally pythonic. See: [How can I decorate all functions of a class without typing it over and over for each method added? Python - duplicate](https://stackoverflow.com/questions/6307761/how-can-i-decorate-all-functions-of-a-class-without-typing-it-over-and-over-for) Also check the answer that this duplicate is pointing to. I personally would prefer a class decorator, since I find that more readable (explicit). – klaas Aug 25 '17 at 05:30
  • You can wrap the methods in the `__new__()` method of the metaclass. – Gribouillis Aug 25 '17 at 05:39
  • Yeah, sorry, I guess it is a duplicate. Thanks. – Charles Langlois Aug 26 '17 at 02:42

0 Answers0