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 ...

Get Django Unleashed now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.