How do you write a decorator that works correctly on BOTH regular functions and methods (instance methods) of a class?
Short answer
Since Python's method binding automatically passes 'self' as the first positional argument when calling through an instance, a decorator using *args/**kwargs to pass arguments through transparently works identically for both plain functions and methods, WITHOUT needing any…
Advertisement
AModel answer
Since Python's method binding automatically passes 'self' as the first positional argument when calling through an instance, a decorator using *args/**kwargs to pass arguments through transparently works identically for both plain functions and methods, WITHOUT needing any special-case handling — the decorator doesn't need to know or care whether it's wrapping a function or a method.
def logged(func):
@functools.wraps(func)
def wrapper(*args, **kwargs): # 'self' arrives as args[0] automatically for methods
print(f"Calling {func.__name__}")
return func(*args, **kwargs)
return wrapper
class Calculator:
@logged
def add(self, a, b): # works identically whether decorated as a function or a method
return a + bReal-world example
Applying the same generic logging or timing decorator uniformly across both standalone functions and class methods.
Likely follow-ups
- Would this same decorator ALSO work correctly on a classmethod or staticmethod without modification?
Related topics