Defensive programming in Python

matt

I love Python, but it's a minefield of a language. Here's some things I do to have confidence in the code I write.

Always log exceptions

Exceptions are the standard path for error reporting in Python, however, I often stumble across code that doesn't make use of logger.exception() when handling exceptions. The result is errors which get eaten by the exception handling.

Use a better logger

The Python standard logger is not my favorite. It's the Denny's of loggers in that it's got something for everyone but nothing I want in particular unless I'm drunk at 1 am. I prefer something like structlog, but anything that doesn't blow up when you pass it a string that's actually None will suffice.

Use typehinting

Typehinting will save your users from fighting runtime errors. It's not a perfect system, but defensive programming isn't about absolute certainty - it's about cutting down on the mole hills that you can trip on.

Check for None

In a language like Python if there's a chance that it can be None then there's a non-zero chance it'll be None for one of your users at some point in the future. It's kind of annoying, but I tend to wrap a none-check around returns from certain libraries that converts them to an exception.

Back to top