Looking before you leap with processor-intensive function
A program can easily waste time by calling a processor-intensive function multiple times.
For example, take a function which looks like this: it returns an integer if the input
value can produce one, else
And it could be used in the following way:
Whilst this will work, it has the problem of calling
intensive_f, which doubles the length of time for the code to run. A better solution would be to get the return value of the function beforehand.
However, a clearer and possibly more pythonic way is to use exceptions, for example:
Here no temporary variable is needed. It may often be preferable to use a
assert statement, and to catch the
A common example of where this may be found is accessing dictionary keys. For example compare:
The first example has to look through the dictionary twice, and as this is a long dictionary, it may take a long time to do so each time. The second only requires one search through the dictionary, and thus saves a lot of processor time.
An alternative to this is to use
dict.get(key, default), however many circumstances may require more complex operations to be done in the case that the key is not present
Overzealous except clause
Exceptions are powerful, but a single overzealous except clause can take it all away in a single line.
This example demonstrates 3 symptoms of the antipattern:
exceptwith no exception type (line 5) will catch even healthy exceptions, including
KeyboardInterrupt. That will prevent the program from exiting in some cases.
- The except block does not reraise the error, meaning that we won't be able to tell if the exception came from within
reswas an empty list.
- Worst of all, if we were worried about result being empty, we've caused something much worse. If
reswill stay completely unset, and the reference to
resin the except block, will raise
NameError, completely masking the original error.
Always think about the type of exception you're trying to handle. Give the exceptions page a read and get a feel for what basic exceptions exist.
Here is a fixed version of the example above:
We catch more specific exceptions, reraising where necessary. A few more lines, but infinitely more correct.