Adding a parameter to a decorator
A common requirement is to customize a decorator with additional parameters. Rather than simply creating a composite
, we can do something a bit more complex. With parameterized decorators, we can create
. We've applied a parameter, c, as part of creating the wrapper,
. This parameterized composite function,
, can then be used with the actual data, x.
In Python syntax, we can write it as follows:
@deco(arg) def func(x): something
There are two steps to this. The first step applies the parameter to an abstract decorator to create a concrete decorator. Then the concrete decorator, the parameterized deco(arg)
function, is applied to the base function definition to create the decorated function.
The effect is as follows:
def func(x): return something(x) concrete_deco = deco(arg) func= concrete_deco(func)
We've done three things, and they are as follows:
- Defined a function,
func()
. - Applied the abstract decorator,
deco()
, to its argument,arg
, to create a concrete...