What's the "pythonic" way of setting default message on custom exception?

Hey,

Can someone help me understand the pythonic way of setting the default message of a custom exception?

Is this the correct way to do so (with docstrings)?

class NoCheeseToEatError(Exception):
    """No cheese to eat from the fridge."""

    def __init__(self, msg=None, *args, **kwargs):
        super().__init__(msg or self.__doc__, *args, **kwargs)
>>> try:
...     raise NoCheeseToEatError
... except NoCheeseToEatError as e:
...     assert(e.__str__() == "No cheese to eat from the fridge.")

>>> try:
...     raise NoCheeseToEatError("Where's the fridge?")
... except NoCheeseToEatError as e:
...     assert(e.__str__() == "Where's the fridge?")
1 Like

__doc__ is set to None if Python is ran under -OO so no, don’t use docstrings for anything functional. Why not just write it in literally? i.e.

super().__init__(msg or "No cheese to eat from the fridge.", *args, **kwargs)

Note that Exception takes no keyword arguments and it doesn’t look like you’re going to use multiple arguments with this subclass so you might as well drop the *args, **kwargs stuff.

1 Like
class NoCheeseToEatError(Exception):
    """Raised when there is no cheese in the container."""

    def __init__(self, msg=None):
        super().__init__(msg or "No cheese to eat from the fridge.")

Thanks, @bwoodsend! That’s a really nice and clean solution. Also makes sense that docstrings could be dropped for optimization, didn’t think about this.