In this lesson, you will learn how to build stateful decorators using the __call__ magic method to manage persistent data across multiple function invocations.
While standard function-based decorators rely on closures to maintain state, class-based decorators offer a more explicit way to store configuration and telemetry data. By implementing __init__ and __call__, you turn an instance of your class into a callable object that behaves exactly like a function.
Designing Stateful Decorators
When you decorate a function with a class, Python calls the class constructor once when the function is defined. The __init__ method receives the function itself, which you can store as an attribute. Later, whenever the decorated function is called, Python invokes the instance’s __call__ method.
This structure is ideal for tracking execution stats, such as counting how many times a function has been triggered.
class CallCounter:
def __init__(self, func):
self.func = func
self.count = 0 # Persistent state
def __call__(self, *args, **kwargs):
self.count += 1
print(f"Call {self.count} for {self.func.__name__}")
return self.func(*args, **kwargs)
@CallCounter
def say_hello():
print("Hello!")
say_hello()
say_hello()
Why use this approach?
Unlike a simple closure, a class-based decorator makes state manipulation highly visible. Because the decorator instance persists for the lifetime of the decorated function, you can inspect or reset self.count at any time from outside the function. This is particularly useful for complex configurations—such as rate-limiting logic, caching layers, or database connection pooling—where you need to manage internal settings that change as your application runs.
By separating the setup logic (in __init__) from the execution logic (in __call__), you create code that is easier to maintain and extend compared to deeply nested function factories.
Key Takeaway: Class-based decorators use the __call__ method to create persistent, stateful wrappers, allowing you to track metrics or manage configurations seamlessly across multiple function executions.