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

Get Python Essentials now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.