Functional Python Programming

(Wang) #1
Chapter 11

Because we can't easily fold in new attributes, it's difficult to locate reasons to modify
or extend the way the wrapping works on a function. It's mostly interesting to use
this variable as a piece of reference information.


If we're going to use the callable objects, then we might have a class that provides
some additional attributes as part of the definition. We could then have a situation
where a decorator might need to copy these additional attributes from the original
wrapped callable object to the wrapping function being created. However, it seems
simpler to make these kinds of changes in the class definition itself, rather than
exploit tricky decorator techniques.


While there's a lot of flexibility available, much of it isn't helpful for ordinary
application development.


Cross-cutting concerns


One general principle behind decorators is to allow us to build a composite function
from the decorator and the original function to which the decorator is applied. The
idea is to have a library of common decorators that can provide implementations for
common concerns.


We often call these cross-cutting concerns because they apply across several
functions. These are the sorts of things that we would like to design once via a
decorator and have them applied in relevant classes throughout an application
or a framework.


Concerns that are often centralized as described previously include the following:



  • Logging

  • Auditing

  • Security

  • Handling incomplete data


A logging decorator, for example, might write standardized messages to the
application's logfile. An audit decorator might write details surrounding a database
update. A security decorator might check some runtime context to be sure that the
login user has the necessary permissions.


Our example of a null-aware wrapper for a function is a cross-cutting concern. In this
case, we'd like to have a number of functions handle the None values by returning
the None values instead of raising an exception. In applications where data is
incomplete, we may have a need to process rows in a simple, uniform way without
having to write lots of distracting if statements to handle missing values.

Free download pdf