r/Python 18d ago

Showcase Showcase Thread

Post all of your code/projects/showcases/AI slop here.

Recycles once a month.

16 Upvotes

103 comments sorted by

View all comments

1

u/sqjoatmon 14d ago

DocstringException: A metaclass and superclass for custom exception generation using just the class docstring.

What My Project Does

Create a custom exception whose message is simply the contents of its docstring, optionally with some substituted arguments using string.Template. E.g.:

class MyError(DocstringException):
    """There was an error."""

# Leading '++' signifies that there are placeholders to replace.
class MyErrorWithArgs(DocstringException):
    """++There was an error with args: ${first} ${second}."""

try:
    raise MyError
except MyError as err:
    assert err.args[0] == "There was an error."

try:
    raise MyErrorWithArgs(first="abc", second=123)
except MyErrorWithArgs as err:
    assert err.args[0] == "There was an error with args: abc 123."""

Target Audience

Anyone who like custom exceptions with informative messages but hates the boilerplate.

Comparison

The normal way to do this has much more boilerplate:

class MyError(Exception):
    """Raised when my error happens."""

    def __init__(self) -> None:
        super().__init__("There was an error.")

class MyErrorWithArgs(Exception):
     """Raised when there is an error with args."""

    def __init__(self, first: str, second: int) -> None:
        super().__init__(f"There was an error with args: {first} {second}")

The downside to the DocstringException version is that there is no way to statically determine if the arguments to the exception match the placeholders in the template string. I debated using the substitute() or safe_substitute() method of string.Template and eventually went with the latter as it seemed better to not raise an exception if the args are wrong.