如何正确弃用 Python 中的自定义异常?

Eli*_*ych 5 python exception deprecated

我的 Python 项目中有自定义继承异常,我想弃用其中之一。正确的做法是什么?

我有例外:

class SDKException(Exception):
    pass

class ChildException(SDKException):
    pass

class ChildChildException(ChildException):  # this one is to be deprecated
    pass
Run Code Online (Sandbox Code Playgroud)

我想弃用 ChildChildException,考虑到该异常在项目中被使用、引发并与其他异常链接在一起。

ale*_*ame 4

您可以使用一个装饰器,它在异常类的每个实例上显示警告类别: DeprecationWarning

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
Run Code Online (Sandbox Code Playgroud)
app.py:7: DeprecationWarning: ChildChildException is deprecated
Run Code Online (Sandbox Code Playgroud)

更新:此外,您还可以创建自定义警告类并将其传递给 warn 函数:

class ExceptionDeprecationWarning(Warning):
    pass
warnings.warn(f"{cls.__name__} is deprecated", ExceptionDeprecationWarning)
Run Code Online (Sandbox Code Playgroud)