B.1 Decorators
A decorator changes the input and output of a callable. It encapsulates or wraps a callable. A decorator is simply another callable that replaces the first and that calls the callable being decorated. It works because Python has first-class functions (read: functions are objects).
For instance, we have a function f() that accepts and returns an integer. If we wanted (for whatever reason) to modify the integer being returned, we could create a new function with the intent of decorating the method, as shown in Example B.1.
Example B.1: Python Code
def f(i): return i def g(func): def new_f(i): r = func(i) return r+10 return new_f
We can see this in action in the Python interpreter, shown in Example ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access