Last Updated: February 25, 2016
·
1.087K
· chewxy

Easier to beg forgiveness than to ask permission

Lots of Python programmers I've met don't really realize that it's easier to beg forgiveness than to ask permission in Python.

def begForgiveness(d, x):
    for k in x:
        try:
            v = d[k]
        except KeyError:
            pass

def askPermission(d, x):
    for k in x:
        if k in d.keys():
            pass
        else:
            pass

If you were to benchmark both codes above, you'll find that begForgiveness() actually executes faster than askPermission(), even on a higher iteration count.

This is because at runtime, Python assumes that keys are there, and if they're not, an exception is raised, which you then catch.

Although this seems like it's rife for abuse (and indeed it is), this should increase performance of those who write code defensively. Type checking for example, is now a simple try:except loop instead of using if type(..).

It's best used when the exception raised is expected.