how do you deprecate a custom exception in python?

You could use a decorator which shows a warning DeprecationWarning category on each instantiation of exception class:

import warnings

warnings.filterwarnings("default", category=DeprecationWarning)

def deprecated(cls):
    original_init = cls.__init__
    def __init__(self, *args, **kwargs):
        warnings.warn(f"{cls.__name__} is deprecated", DeprecationWarning, stacklevel=2)
        original_init(self, *args, **kwargs)
    cls.__init__ = __init__
    return cls

class SDKException(Exception):

class ChildException(SDKException):

class ChildChildException(ChildException):  # this one is to be deprecated

    raise ChildChildException()    
except ChildChildException:
    pass DeprecationWarning: ChildChildException is deprecated

Update: Also, you can create custom warning class and pass it to the warn function:

class ExceptionDeprecationWarning(Warning):
warnings.warn(f"{cls.__name__} is deprecated", ExceptionDeprecationWarning)

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top