r/Python • • Nov 14 '17

Senior Python Programmers, what tricks do you want to impart to us young guns?

Like basic looping, performance improvement, etc.

1.3k Upvotes

629 comments sorted by

View all comments

2

u/flatlander_ Nov 14 '17 edited Nov 16 '17

When you do a try: except:, make sure that you at least except Exception, or you could run into weird issues like not being able to stop your program. This is because KeyboardInterrupt, SystemExit et al are derived from BaseException and will be swallowed if you don't except them or a superclass.

e.g. do this:

try:
    some_risky_thing()
except Exception:
    pass

and not this:

try:
    some_risky_thing()
except:
    pass

4

u/filletrall Nov 14 '17

I find a good rule of thumb is to only catch exceptions when I know specifically what exception will be raised by my code.

If I don't know precisely what exception I will get, I resist the temptation to guess and just leave out the try-clause for the time being. When I trigger the exception later on I will add it. If there are several exceptions that I want to treat the same, then:

try:
    result = getattr(obj, attr)[index]
except (LookupError, AttributeError):
    result = default

1

u/cr4d Nov 14 '17

Bare exceptions are generally a bad idea. Other people have summarized why better than I can:

I like this simple summary from https://jeffknupp.com/blog/2013/02/06/write-cleaner-python-use-exceptions/:

Never use a "bare" except: clause or you'll end up suppressing real errors you didn't intend to catch.

1

u/[deleted] Nov 14 '17

Except don’t use “except Exception” and choose a reasonable Exception type for the situation - using “except Exception” is exactly the same as “except:”

4

u/TravisJungroth Nov 14 '17

They're not the same. KeyboardInterrupt doesn't inherit from Exception so it won't be caught by except Exception:.

except: is the same as except BaseException:.

https://docs.python.org/3/library/exceptions.html#exception-hierarchy

However, I do agree it's a good idea to be more specific in exception catching.

2

u/[deleted] Nov 14 '17

Apologies for being unclear. My intention was to suggest that it’s better to be more specific because you definitely don’t want to get stuck debugging issues where “except Exception” ends up catching unexpected errors, and that “except:” is about the same level of bad as the former from that perspective.