Functional Python Programming

(Wang) #1

Decorator Design Techniques


This function wraps a given conversion function to try a second conversion in the
event the first conversion involved bad data. In the case of preserving the None
values as a Not Applicable code, the exception handling would simply return the
None value.


In this case, we've provided Python *args and **kw parameters. This assures that
the wrapped functions can have additional argument values provided.


We can use this wrapper as follows:


bd_int= bad_data(int)


bd_float= bad_data(float)


bd_decimal= bad_data(Decimal)


This will create a suite of functions that can do conversions of good data as well as a
limited amount of data cleansing to handle specific kinds of bad data.


Following are some examples of using the bd_int() function:





bd_int("13")





13





bd_int("1,371")





1371





bd_int("1,371", base=16)





4977


We've applied the bd_int() function to a string that converted neatly and a string
with the specific type of punctuation that we'll tolerate. We've also shown that we
can provide additional parameters to each of these conversion functions.


We might like to have a more flexible decorator. One feature that we might like to
add is the ability to handle a variety of data scrubbing alternatives. Simple, removal
isn't always what we need. We may also need to remove $, or ° symbols, too. We'll
look at more sophisticated, parameterized decorators in the next section.


Adding a parameter to a decorator


A common requirement is to customize a decorator with additional parameters.
Rather than simply creating a composite fgx (), we're doing something a bit more
complex. We're creating ()fcgx()i (). We've applied a parameter, c, as part of creating
the wrapper. This parameterized composite,fcg() , can then be used with the actual
data, x.

Free download pdf