Python applies a decorator to every method in the class without checking

Slightly changing the answer from Applying python decorators to methods in a class , you can apply a decorator to each method in the class. Is there a way to do this without a validation module? I tried to accomplish this using metaclasses and modifying __getattribute__, but I keep getting infinite recursion. From How is the __getattribute__ Method Used? , this can be fixed in regular classes using the .__ getattribute __ (self, name) object. Is there something equivalent for metaclasses?

0
python metaclass class decorator
source share
1 answer

Define a meta class, and then simply apply a decorator at the end of the class definition.

class Classname: def foo(self): pass for name, fn in inspect.getmembers(Classname): if isinstance(fn, types.UnboundMethodType): setattr(Classname, name, decorator(fn)) 

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

but if you really don't want to use an inspector, you can do it like

 import types class DecoMeta(type): def __new__(cls, name, bases, attrs): for attr_name, attr_value in attrs.iteritems(): if isinstance(attr_value, types.FunctionType): attrs[attr_name] = cls.deco(attr_value) return super(DecoMeta, cls).__new__(cls, name, bases, attrs) @classmethod def deco(cls, func): def wrapper(*args, **kwargs): print "before",func.func_name func(*args, **kwargs) print "after",func.func_name return wrapper class MyKlass(object): __metaclass__ = DecoMeta def func1(self): pass MyKlass().func1() 

Output:

before func1 after func1

Note: it will not decorate staticmethod and classmethod

+3
source share

All Articles