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:
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): process_file(p) else: ...some exception code...
- 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' try: process_file(p) 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.
- Hitchhiker’s Guide to Python
- Code like a Pythonista
- Learn the Pythonic Way
- Microsoft: EAFP vs LBYL
- Jeff Knupp: Write Cleaner Python