Make your Python code more readable with custom exception classes
In this short screencast I’ll walk you through a simple code example that demonstrates how you can use custom exception classes in your Python code to make it easier to understand, easier to debug, and more maintainable.
Let’s say we want to validate an input string representing a person’s name in our application. A simple toy example might look like this:
defvalidate(name):iflen(name)<10:raiseValueError
If the validation fails it throws a ValueError
. That feels kind of Pythonic already… We’re doing great!
However, there’s one downside to this piece of code: Imagine one of our team mates calls this function as part of a library and doesn’t know much about its internals.
When a name fails to validate it’ll look like this in the debug stacktrace:
>>>validate('joe')Traceback(mostrecentcalllast):File"<input>",line1,in<module>validate('joe')File"<input>",line3,invalidateraiseValueErrorValueError
This stacktrace isn’t really all that helpful. Sure, we know that something went wrong and that the problem has to do with an “incorrect value” of sorts.
But to be able to fix the problem our team mate almost certainly has to look up the implementation of validate()
. But reading code costs time. And it adds up quickly…
Luckily we can do better! Let’s introduce a custom exception type for when a name fails validation. We’ll base our new exception class on Python’s built-in ValueError
, but make it more explicit by giving it a different name:
classNameTooShortError(ValueError):passdefvalidate(name):iflen(name)<10:raiseNameTooShortError(name)
See how we’re passing name
to the constructor of our custom exception class when we instantiate it inside validate
? The updated code results in a much nicer stacktrace for our team mate:
>>>validate('jane')Traceback(mostrecentcalllast):File"<input>",line1,in<module>validate('jane')File"<input>",line3,invalidateraiseNameTooShortError(name)NameTooShortError:jane
Now, imagine you are the team mate we were talking about… Even if you’re working on a code base by yourself, custom exception classes will make it easier to understand what’s going on when things go wrong. A few weeks or months down the road you’ll have a much easier time maintaing your code. I’ll vouch for that 😃
P.S. If you enjoyed this screencast and you’d like to see more just like it then subscribe to my » YouTube channel with free screencasts and video tutorials for Python developers«