Pythonic Zen: Failures and Exceptions

From my initial learnings on  Python, I have been struck by the message that there is a very strong sense of things being Pythonic, i.e.there being a Python-way of doing things.

Here I’m going to talk about coding for failures.

There are two approaches dealing with program execution and an operation which might fail:

  • LBYL
  • EAFP

Look Before You Leap – Check that all possible failure conditions for a failure-prone operation are met in advance of attempting the operation.

It’s Easier to Ask Forgiveness than Permission – Hope for the best and deal with the consequences.

In a simple example, this might mean that rather than doing a whole bunch of type checking on an object passed before doing an action (LBYL), it is a preferred approach to try to do it and then catch the exceptions if it fails (EAFP).

Below is another example. Consider some noddy LBYP code which processes a file:

import os
p = '/mypath/myfile.txt'
if os.path.exists(p):
    ...some exception code...

Problems include:

  • if check clutters the “happy path” through the code
  • ‘exists’ is only one of quite a few conditions we might check
  • something might happen to our file between the check and the process such that the file would no longer pass the checks so we have to code for the exception anyway.

Compare and contrast the EAFP approach:

p = '/mypath/myfile.txt'
except OSError as e:
    ...some exception code...

EAFP in conjunction with Exceptions, rather than bespoke error/return codes, is considered to be the Pythonic way.

Further reading:


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s