Functional Python Programming

(Wang) #1

Decorator Design Techniques


For this reason, it is often necessary to provide a separate cleansing function that's
bundled in with the conversion function. This function will handle the more
sophisticated conversions required by inputs that are as wildly inconsistent
in format as latitudes and longitudes.


How can we implement this? We have a number of choices. Simple higher-order
functions are a good choice. A decorator, on the other hand, doesn't work out terribly
well. We'll look at a decorator-based design to see that there are limitations to what
makes sense in a decorator.


The requirements have two orthogonal design considerations and they are
as follows:



  1. The output conversion (int, float, Decimal)

  2. The input cleaning (clean stray characters, reformat coordinates)


Ideally, one of these aspects is an essential function that gets wrapped and the other
aspect is something that's included via a wrapper. The choice of essence versus wrap
isn't clear. One of the reasons it isn't clear is that our previous examples are a bit
more complex than a simple two-part composite.


In the previous examples, we were actually creating a three-part composite:



  • The output conversion (int, float, Decimal)

  • The input cleansing—either a simple replace or a more complex
    multiple-character replacement

  • The function which attempted the conversion, did the cleansing as a response
    to an exception, and attempted the conversion again


The third part – attempting the conversion and retrying – is the actual wrapper that
also forms a part of the composite function. As we noted previously, a wrapper
contains a before phase and an after phase, which we've called wxα() and wxβ(),
respectively.


We want to use this wrapper to create a composite of two additional functions.
We have two choices for the syntax. We could include the cleansing function
as an argument to the decorator on the conversion as follows:


@cleanse_before(cleanser)


def convert(text):


something

Free download pdf