Attaching a decorator to all functions within a class

dochead :

I don't really need to do this, but was just wondering, is there a way to bind a decorator to all functions within a class generically, rather than explicitly stating it for every function.

I suppose it then becomes a kind of aspect, rather than a decorator and it does feel a bit odd, but was thinking for something like timing or auth it'd be pretty neat.

Duncan :

The cleanest way to do this, or to do other modifications to a class definition, is to define a metaclass.

Alternatively, just apply your decorator at the end of the class definition:

class Something:
   def foo(self): pass

for name, fn in inspect.getmembers(Something):
    if isinstance(fn, types.UnboundMethodType):
        setattr(Something, name, decorator(fn))

For Python 3 replace types.UnboundMethodType with types.FunctionType.

In practice of course you'll want to apply your decorator more selectively. As soon as you want to decorate all but one method you'll discover that it is easier and more flexible just to use the decorator syntax in the traditional way.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

How to register within a decorator all functions it decorates?

Is there a way to get all functions of a class with the decorator "@property"?

How to define decorator within the class?

Patch all functions in module with decorator

Decorator for both class methods and functions

parse python functions as a string within decorator

abstractmethod decorator to all methods in class

recursive functions within the class

Using functions within a class

Use an instance method as a decorator within another class

Implementing a decorator within class "major flaw"?

How to use a decorator of a descriptor within a sub class

Get Class Instance from Within Decorator

python decorator - registering class within base

Hot to get the `this` from a class within it's decorator

How to apply a decorator to all class methods using class decorator

Finding all anchors in a page and attaching functions without jquery

Decorator Causing All Functions to Return True

Class as a decorator for regular functions and coroutines in Python

Python decorator within function, needs class within method?

Are variables in the function within a class shared between all other functions enclosed in that class in Python?

Python - Pass class as argument to decorator of method within that class?

Change the docstring of a class method within a decorator based on class attribute

Scoping functions within namespace versus within class

Check functions within class for True

Typescript :: namespacing functions within a class?

Javascript Class - Function Optimisation (Functions Within Functions)

Access an injected service from within a Class decorator? Typescript / NestJS

Pylint throws not-callable on decorator defined within class