Stateful decorators in wrapt - Graham Dumpleton
Briefly

Stateful decorators in wrapt - Graham Dumpleton
Wrapt 2.2.0 introduces a helper that makes stateful decorators easier to implement. A stateful decorator wraps a function and retains information across invocations, such as call counts, timing statistics, cached results, seen arguments, or registries of actions. The main challenge is not maintaining bookkeeping but exposing the stored state to callers. If state never needs to be inspected, it can remain in a closure. If callers must query internal state, the decorator needs a mechanism to access that state from outside. A common plain-Python approach stores state on the wrapper function as an attribute, but applying the same pattern to instance methods introduces additional complexity.
"Version 2.2.0 introduces a small helper that makes it noticeably easier to write decorators that need to keep state across calls. It is the kind of thing that does not look like much until you try to write the equivalent code without it, so it is worth a closer look."
"The complication is not the bookkeeping itself, it is exposing the state back to the caller. If a decorator is purely passive and does its work without anyone ever needing to look at the internals, state can live in a closure and nobody is any the wiser. Once you decide that the user of the decorated function should be able to ask "how many times has this been called?", you need a way to reach into that state from the outside."
"The simplest pattern in plain Python is to push state onto the wrapper function as an attribute: import functools def call_tracker(func): @functools.wraps(func) def wrapper(*args, **kwargs): try: return func(*args, **kwargs) finally: wrapper.call_count += 1 wrapper.call_count = 0 return wrapper @call_tracker def add(x, y): return x + y add(1, 2) add(3, 4) print(add.call_count) Running this prints 2."
"That works fine for a regular function, but the moment you apply the same decorator to an instance method things get more subtle. T"
Read at Grahamdumpleton
Unable to calculate read time
[
|
]