Logo

dev-resources.site

for different kinds of informations.

documented: make docstrings in your exceptions work

Published at
10/6/2023
Categories
python
exceptions
opensource
libraries
Author
anatolyscherbakov
Author
17 person written this
anatolyscherbakov
open
documented: make docstrings in your exceptions work

During my time in writing Python code, I have gone through a certain evolution; one of the aspects of it is how I create and manage exceptions.

Level 0

raise ValueError("I'm sorry Dave. I'm afraid I can't do that.")
Enter fullscreen mode Exit fullscreen mode

Here, to signify an error, we just use a standard built-in error class (such as Exception or ValueError). The exception message will be printed to the log and/or provided to the user.

If we would like to catch the exception and to base our future behavior on the particular error that we had caught then we will be in trouble; likely we'll have to manually parse the exception message. That's dirty.

Level 1

class PodBayDoorsStillClosed(ValueError):
    pass

# …

raise PodBayDoorsStillClosed("I'm sorry Dave. I'm afraid I can't do that.")
Enter fullscreen mode Exit fullscreen mode

Now, I can catch PodBayDoorsStillClosed in some other place of the application, and modify my behavior based on that. For instance, I can

try:
    ...
except PodBayDoorsStillClosed:
    retry()
Enter fullscreen mode Exit fullscreen mode

It is unlikely that HAL complies but at least the code will be arguably a bit more expressive.

Level 2

At some point, I realize that the text of HAL's message belongs to the class of the exception; there is no reason to keep them apart.

class PodBayDoorsStillClosed(ValueError):
    def __str__(self):
        return "I'm sorry Dave. I'm afraid I can't do that."

# …

raise PodBayDoorsStillClosed()
Enter fullscreen mode Exit fullscreen mode

This is better, but… is it cool to write __str__ all the time, for each exception message, separately? — No, decidedly not.

Level ∞

Some time ago I wrote a very small Python library by the name of documented. Which makes it look like this:

@dataclass
class PodBayDoorsStillClosed(DocumentedError):
    """
    I’m sorry, {self.user_name}.

    I’m afraid I can’t do that.
    """

    user_name: str

# …

raise PodBayDoorsStillClosed('Dave')
Enter fullscreen mode Exit fullscreen mode

That will print:

PodBayDoorsStillClosed: I’m sorry, Dave.

I’m afraid I can’t do that.
Enter fullscreen mode Exit fullscreen mode

I am now using it to format both internal and external exceptions for web and console applications. Flight condition nominal, so far. Perhaps this library will be useful for you too; you can easily grab it via

pip install documented
Enter fullscreen mode Exit fullscreen mode

Links

libraries Article's
30 articles in total
Favicon
Top 5 Python Libraries to Watch in 2025
Favicon
The Use of TeeChart Charting Libraries in EMD International’s Renewable Energy Solutions
Favicon
Common Java Libraries and Frameworks you Should Try
Favicon
TeeChart Charting Libraries use cases
Favicon
Scientific problems are not real problems for programmers
Favicon
Top 8 AI Open Source Software Libraries
Favicon
How to Create a Library Package from an existing Angular App
Favicon
New in ngx-errors 4.0
Favicon
List of awesome CSS frameworks, libraries and software
Favicon
NPM libraries to build your next AI projects
Favicon
How to use external libraries in Theme App Extensions for your Shopify App
Favicon
What are headless UI libraries?
Favicon
Best Javascript Machine Learning Libraries in 2024
Favicon
5 C# Word Libraries Most .NET Developers Use in Project
Favicon
C# PDF Libraries Compared for .NET Developers: Pros & Cons
Favicon
Essential AI Tools and Libraries: A Guide to Python, Git, C++ Compile Tools, FFmpeg, CUDA, PyTorch
Favicon
8 Python Libraries You Might Not Be Using But Should
Favicon
documented: make docstrings in your exceptions work
Favicon
32 Best Passkey Libraries
Favicon
Can I access the JavaScript native Math library source code?
Favicon
What’s the difference between a library and a framework?
Favicon
Comparing React Testing Libraries
Favicon
Exploring CDN Links for CanvasJS Charts and Stockcharts
Favicon
Backup manually installed libraries and packages in Ubuntu
Favicon
What is your favorite web development tool or framework, and what makes it valuable to you?
Favicon
Only internally vetted and approved Open Source libraries can be used
Favicon
Top Libraries Used for React JS Rendering
Favicon
A Brief Overdrive Library Analysis
Favicon
Top 10 technologies/framework to learn as a MERN stack developer in 2023
Favicon
Why is State Management Important For React Apps?

Featured ones: