Make your Python Code More Readable with Custom Exceptions
Key Takeaways
The video demonstrates how to create custom exception classes in Python to make code more readable and maintainable, using a simple example of a validate function that checks the length of a name.
Full Transcript
hey guys it's Daniel with another quick python tip for you so today I want to talk about how you can make your code more readable using custom exceptions um so to give you an example when you might want to do that uh let's say we have a simple function here we're going to call it validate and we're going to pass it a name which is just a simple string variable and that function is going to do a simple check on um name just to see if um if it's less than 10 characters long right and if it's less than 10 characters long we want to reject that name because we're just going to say hey you know what it's not a valid name so uh one way to communicate that to um someone who might be calling that function you know one of your co-workers um maybe you're going to call that function yourself somewhere in the code I mean it's highly likely considering that we're writing the function um what's the best way to communicate that right sure we could just return none H it's kind of easy to miss and just ignore that so typically what you do is you'd raise an exception um and we would probably pick something like uh Python's built-in value error right and um so what would happen now is that when we take this function and we call it on a name that's less than 10 characters wrong uh long we get a value error so let's take a look at what that looks like so let's define validate here and we're just going to call validate on uh a three character name here and we get the Val ER value error right that's sort of the error report that we would get in in a trace back uh when our program crashes um that's okay you could probably use that to trace it back to the line you were working in you could kind of figure out why you got that value error maybe um a way to to make that a little bit more clear and just to communicate the intent a little better would be to say okay we're going to do a value error and uh we're going to tell you that the name is too short so if you do that what happens is um that you get a little bit of more context right we're going to tell you hey the name is too short so the downside of that is um programmatically it becomes really difficult to distinguish between you know a name too short kind of value error and just any other old value ER so that's not great but there's a really good way to fix this that I'm going to show you now so what you would do in this case is you would create a new um subass of value error and we're going to call that um name to short error and that's going to be based on the original value error and because we're not you know we're not even trying to add more stuff to Value error we're not going to add extra for behaviors or properties so we're just going to say pass here to leave the class alone but what we've done now we've created a new type that we can now actually use in um our code here and um what's cool about this now is that when we when someone runs this code and they actually trigger the condition that raises the value error they will get a name to short error right you get that initial console because I'm running this in inside the Python 3 interpreter here but um it gives someone who hits that error a bit more context um and tells them the the original programmer's intent right you're going to be able to quickly figure out oh okay you know this is being triggered because the name was too short and we can make this a little nicer still so what I like to do in uh in a situation like this is to actually pass the uh value that cost the error to um my custom exception type right so um in this case we would obviously pass name and then when we run this in the python reppel you will see that uh the error report is kind of nice at this point because you know if this blows up this is what you would see eventually in your in your uh Trace back when when you get uh the the the exception printed out at some point um you would see something like that name to short error Joe um and that was cost invalidate so at this point it would be really easy for someone else or maybe your your future self to identify what went wrong here and um you're probably going to save yourself more time then the time it you know then the time it took you to to go and Define that custom exception type so as with all things you know it's not something you should overdo but it can be extremely helpful especially if you're defining um a public API for for um let's say a module that you want to share with other people um that sort of stuff is going to save you tons of time and it's just going to make you a lot more productive as a developer cool I hope this helped you out uh take care and write more python
Original Description
How to make your Python code more readable with custom exception classes. In this 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.
► Weekly Tips for Python Developers: https://dbader.org/newsletter
Watch on YouTube ↗
(saves to browser)
Sign in to unlock AI tutor explanation · ⚡30
Playlist
Uploads from Real Python · Real Python · 7 of 60
1
2
3
4
5
6
▶
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
A better Python REPL – bpython vs python interpreter
Real Python
Introducing large-type.com – A Utility Website
Real Python
Reading Hacker News Without Wasting Tons of Time
Real Python
Forward References and Python 3 Type Hints
Real Python
Using Sublime Text as your Git Editor
Real Python
Python Code Linting and Auto-Complete for Sublime Text
Real Python
Make your Python Code More Readable with Custom Exceptions
Real Python
Write Better Tests with Sublime Text's Split Layout Feature
Real Python
How to Use Sublime Text from the Command Line
Real Python
Rename Variables with Multiple Selection in Sublime Text
Real Python
Sublime Text Settings for Writing PEP 8 Python
Real Python
Write Cleaner Python with Sublime Text's Indent Guides
Real Python
Sublime Text Whitespace Settings for Python Development
Real Python
Function Argument Unpacking in Python
Real Python
Python Code Review: Debugging and Refactoring "Conway's Game of Life" + Automated Tests
Real Python
Using "get()" to Return a Default Value from a Python Dict
Real Python
A Python Shorthand for Swapping Two Variables
Real Python
Python Code Review: Refactoring a Web Scraper, PEP 8 Style Guide Compliance, requirements.txt
Real Python
Click & Jump to Test Failures from the Command Line (iTerm2)
Real Python
Setting up Sublime Text for Python Developers
Real Python
Sublime Text + Python Guide Overview
Real Python
Python Code Review: Adding Pytest Tests to an Existing Python Web Scraper
Real Python
Type-Checking Python Programs With Type Hints and mypy
Real Python
A Shorthand for Merging Dictionaries in Python 3.5+
Real Python
Python Code Review Flask Web Security Tutorial + Virtualenvs, requirements.txt
Real Python
My Python Code Looks Ugly and Confusing – Help!
Real Python
Setting Up a Programmer Portfolio/Developer Blog – How To Get Started
Real Python
Do I Need a GitHub/GitLab/Bitbucket Profile as a Developer?
Real Python
Programmer Portfolio – Example and Walkthrough
Real Python
How to Get Your 1st Speaking Gig at a Tech Conference
Real Python
How to Build Your Public Speaking Skills as a Developer
Real Python
The Object-oriented Version of "Spaghetti Code" is "Lasagna Code" ?!
Real Python
Setting up Sublime Text for Python Developers – Lesson #1
Real Python
Cool New Features in Python 3.6
Real Python
"is" vs "==" in Python – What's the Difference? (And When to Use Each)
Real Python
Emulating switch/case Statements in Python with Dictionaries
Real Python
Python Function Argument Unpacking Tutorial (* and ** Operators)
Real Python
What Code Should I Put On My GitHub/GitLab/BitBucket Profile?
Real Python
A Crazy Python Dictionary Expression ?!
Real Python
String Conversion in Python: When to Use __repr__ vs __str__
Real Python
Method Types in Python OOP: @classmethod, @staticmethod, and Instance Methods
Real Python
Optional Arguments in Python With *args and **kwargs
Real Python
Python Context Managers and the "with" Statement (__enter__ & __exit__)
Real Python
Installing Python Packages with pip and virtualenv / venv
Real Python
"For Each" Loops in Python with enumerate() and range()
Real Python
Python Code Review: LibreOffice Automation and the Python Standard Library
Real Python
Managing Python Dependencies With Pip and Virtual Environments – Lesson #1
Real Python
Python Tutorial: List Comprehensions Step-By-Step
Real Python
Leveraging Python's Implicit "return None" Statements
Real Python
What's the meaning of underscores (_ & __) in Python variable names?
Real Python
Python Data Structures: Sets, Frozensets, and Multisets (Bags)
Real Python
Writing automated tests for Python command-line apps and scripts
Real Python
How to find great Python packages on PyPI, the Python Package Repository
Real Python
Immutable vs Mutable Objects in Python
Real Python
PyPI vs Warehouse, the Next-Generation Python Package Repository
Real Python
pep8.org — The Prettiest Way to View the PEP 8 Python Style Guide
Real Python
My Experience at PyCon 2017 in Portland
Real Python
Pylint Tutorial – How to Write Clean Python
Real Python
"Reverse a List in Python" Tutorial: Three Methods & How-to Demos
Real Python
Python Refactoring: "while True" Infinite Loops & The "input" Function
Real Python
More on: Python for Data
View skill →Related AI Lessons
🎓
Tutor Explanation
DeepCamp AI