Permission versus forgiveness – a Pythonic approach
A common piece of Pythonic wisdom is the following advice from RADM Grace Murray Hopper:
"It is Easier to Ask for Forgiveness than Permission"
In the Python community, this is sometimes summarized as EAFP programming. This is in contrast to Look Before You Leap (LBYL) programming.
Python exception handling is fast. More importantly, all of the necessary precondition checks for potential problems are already part of the language itself. We never need to bracket processing with extraneous if
statements to see whether or not the input could possibly raise an exception.
It's generally considered a bad practice to write LBYL code that looks like this:
if text.isdigit(): num= int(text) else: num= None
The bad idea shown here is an attempt to check carefully to prevent an exception from being raised. This is ineffective for a number of reasons.
The
isdigit()
test fails to properly handle negative numbers. For afloat()
conversion, this kind of...