Preserve Method Binding in Decorators
Core idea
Functions stored on a class bind the instance when accessed as methods. A wrapper returned as a function receives self through normal binding. For a class method, place @classmethod outside an ordinary function wrapper so that the descriptor binds cls to the wrapper. A static method has no automatically supplied instance or class argument.
from functools import wrapsdef trace(fn): @wraps(fn) def wrapper(*args, **kwargs): print('method') return fn(*args, **kwargs) return wrapperclass Counter: def __init__(self, value): self.value = value @trace def read(self): return self.valueprint(Counter(8).read())The bound instance is the first argument of wrapper.
Wrap before classmethod
def tagged(fn): def wrapper(*args, **kwargs): return '[' + fn(*args, **kwargs) + ']' return wrapperclass Device: @classmethod @tagged def label(cls): return cls.__name__print(Device.label())classmethod wraps the function produced by tagged and binds cls.
Common mistake
An arbitrary callable object returned by a decorator may not implement method binding. Do not assume descriptors and plain functions can be wrapped in either order.
Practice
Add a static method with @staticmethod outside trace; compare arguments with an instance method.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Method decorators
Check your understanding of method decorators.
What is printed?
def d(f): return lambda self: f(self)+1class C: @d def n(self): return 4print(C().n())What is printed?
class C: @classmethod def name(cls): return cls.__name__class D(C): passprint(D.name())What does an ordinary bound instance method receive first?
Where should classmethod sit for a plain function wrapper?