Functional Python Programming

(Wang) #1

Decorator Design Techniques


Python offers us many ways to create higher-order functions. In Chapter 5,
Higher-order Functions, we looked at two techniques: defining a function which
accepts a function as an argument and defining a subclass of Callable which is
either initialized with a function or called with a function as an argument.


In this chapter, we'll look at using a decorator to build a function based on
another function. We'll also look at two functions from the functools module,
the update_wrapper() and wraps() functions, that can help us build decorators.


One of the benefits of decorated functions is that we can create composite
functions. These are single functions that embody functionality from several
sources. A composite function, fgx (), can be somewhat more expressive of
a complex algorithm than fgx()(). It's often helpful to have a number of syntax
alternatives for expressing complex processing.


Decorators as higher-order functions


The core idea of a decorator is to transform some original function into another form.
A decorator creates a kind of composite function based on the decorator and the
original function being decorated.


A decorator function can be used in one of the two following ways:



  • As a prefix that creates a new function with the same name as the base
    function as follows:
    @decorator
    def original_function():
    pass

Free download pdf