| Start |
|---|
| 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:
Always think about the type of exception you're trying to handle. Give the exceptions page a read (opens new window) 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. |
| 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 And it could be used in the following way: Whilst this will work, it has the problem of calling However, a clearer and possibly more pythonic way (opens new window) is to use exceptions, for example: Here no temporary variable is needed. It may often be preferable to use a Dictionary keysA common example of where this may be found is accessing dictionary keys. For example compare: with: 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 |
Read Article
https://develop.horje.com/learn/1434/reference