pythonexceptiondeprecated

How to properly deprecate a custom exception in Python?


I have custom inheriting exceptions in my Python project and I want to deprecate one of them. What is the proper way of doing it?

Exceptions I have:

class SDKException(Exception):
    pass

class ChildException(SDKException):
    pass

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

I want to deprecate the ChildChildException, considering the exception is used, raised and chained with other exceptions in the project.


Solution

  • 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):
        pass
    
    
    class ChildException(SDKException):
        pass
    
    @deprecated
    class ChildChildException(ChildException):  # this one is to be deprecated
        pass
    
    try:
        raise ChildChildException()    
    except ChildChildException:
        pass
    
    app.py:7: DeprecationWarning: ChildChildException is deprecated
    

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

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