Imprudent return codes

Let's add a second function, string_log() to our module, which calls our convert() function and computes the natural log of the result:

from math import log

def string_log(s):
v = convert(s)
return log(v)

At this point we must confess that we've gone out of our way here to be deeply unPythonic by wrapping the perfectly good int() conversion, which raises exceptions on failure, in our convert() function which returns a good old-fashioned negative error code. Rest assured that this unforgivable Python heresy has been committed solely to demonstrate the greatest folly of error return codes: That they can be ignored by the caller, wreaking havoc amongst unsuspecting code later in the program. A slightly better program might test the value of v before proceeding to the log call.

Without such a check log() will of course fail when passed the negative error code value:

>>> from exceptional import string_log
>>> string_log("ouch!")
Conversion error: invalid literal for int() with base 10: 'ouch!'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "./exceptional.py", line 15, in string_log
return log(v)
ValueError: math domain error

Naturally, the consequence of the log() failure is the raising of another exception, also a ValueError.

Much better, and altogether more Pythonic, to forget about error return codes completely and revert to raising an exception from convert().

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset