Adding a parameter to a decorator
A common requirement is to customize a decorator with additional parameters. Rather than simply creating a composite
![](https://static.packt-cdn.com/products/9781788627061/graphics/f7b22cfc-aba9-407e-956c-904813804212.png)
, we can do something a bit more complex. With parameterized decorators, we can create
![](https://static.packt-cdn.com/products/9781788627061/graphics/9df9d973-e635-411a-95ab-63a1540a1cc5.png)
. We've applied a parameter, c, as part of creating the wrapper,
![](https://static.packt-cdn.com/products/9781788627061/graphics/71cb9442-536f-46e6-8b48-f1ed6090fcb5.png)
. This parameterized composite function,
![](https://static.packt-cdn.com/products/9781788627061/graphics/2bc0e4e9-b96d-4e80-8ccd-ce00b1e157dc.png)
, 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...