How to raise a DeprecationWarning when catching an exception with python?

Viewed 1541

I wrote a library that sometimes raises exceptions. There is an exception that I want to deprecate, and I would like to advise people to stop catching them, and provide advises in the warning message. But how to make an exception emit a DeprecationWarning when catched?

library code

import warnings

class MyException(ValueError):
    ...
    warnings.warn(
        "MyException is deprecated and will soon be replaced by `ValueError`.",
        DeprecationWarning,
        stacklevel=2,
    )
    ...

def something():
    raise MyException()

user code

try:
    mylib.something()
except MyException: # <-- raise a DeprecationWarning here
    pass

How can I modify MyException to achieve this?

2 Answers

You can't. None of the logic that occurs in except MyException is customizable. Particularly, it completely ignores things like __instancecheck__ or __subclasscheck__, so you can't hook into the process of determining whether an exception matches an exception class.

The closest you can get is having the warning happen when a user tries to access your exception class with from yourmodule import MyException or yourmodule.MyException. You can do that with a module __getattr__:

class MyException(ValueError):
    ...

# access _MyException instead of MyException to avoid warning
# useful if other submodules of a package need to use this exception
# also use _MyException within this file - module __getattr__ won't apply.
_MyException = MyException
del MyException

def __getattr__(name):
    if name == 'MyException':
        # issue warning
        return _MyException
    raise AttributeError

Try using this:

import warnings


class MyOtherException(Exception):
    pass


class MyException(MyOtherException):
    def __init__(self):
        warnings.warn(
            "MyException is deprecated and will soon be replaced by `MyOtherException`.",
            DeprecationWarning,
            stacklevel=2,
        )


if __name__ == "__main__":
    try:
        mylib.something()
    except Exception:
        raise MyException()


Related