Chapter 11
In Python syntax, we can write it as follows:
@deco(arg)
def func( ):
something
This will provide a parameterized deco(arg) function to the base function definition.
The effect is as follows:
def func( ):
something
func= deco(arg)(func)
We've done three things and they are as follows:
- Define a function, func.
- Apply the abstract decorator, deco(), to its arguments to create a concrete
decorator, deco(arg). - Apply the concrete decorator, deco(arg), to the base function to create the
decorated version of the function, deco(arg)(func).
A decorator with arguments involves indirect construction of the final function.
We seem to have moved beyond merely higher-order functions into something
even more abstract: higher-order functions that create higher-order functions.
We can expand our bad-data aware decorator to create a slightly more flexible
conversion. We'll define a decorator that can accept parameters of characters to
remove. Following is a parameterized decorator:
import decimal
def bad_char_remove(char_list):
def cr_decorator(function):
@wraps(function)
def wrap_char_remove(text, args, kw):
try:
return function(text, *args, *kw)
except (ValueError, decimal.InvalidOperation):
cleaned= clean_list(text, char_list)
return function(cleaned, args, kw)
return wrap_char_remove
return cr_decorator