Configure Decorators with Factories
Core idea
A parameterized decorator is a factory: calling it with configuration returns a decorator; applying that decorator returns a wrapper. The wrapper closes over configuration and the original function. Validate configuration when the factory runs, before calls begin.
from functools import wrapsdef prefix(tag): def decorate(fn): @wraps(fn) def wrapper(*args, **kwargs): return tag + fn(*args, **kwargs) return wrapper return decorate@prefix('OK: ')def report(): return 'ready'print(report())The factory fixes tag and the wrapper calls report later.
Two configurations
def scale(k): def decorate(fn): def wrapper(x): return k * fn(x) return wrapper return decorate@scale(2)def a(x): return x + 1@scale(3)def b(x): return x + 1print(a(4), b(4))Each factory call keeps its own multiplier.
Common mistake
Do not confuse @scale with @scale(2). The first passes a function as configuration instead of applying the configured decorator.
Practice
Create a factory that adds a fixed numeric offset to a result, and apply it with two different offsets.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Parameterized decorators
Check your understanding of parameterized decorators.
What is printed?
def factory(n): return lambda f: lambda: n+f()@factory(4)def f(): return 2print(f())What is printed?
def factory(n): return lambda f: lambda x: f(x)*nd=factory(3)print(d(lambda x:x+2)(4))What does factory(config) return?
When should invalid configuration be rejected?