我的 Python 项目中有自定义继承异常,我想弃用其中之一。正确的做法是什么?
我有异常(exception):
class SDKException(Exception):
pass
class ChildException(SDKException):
pass
class ChildChildException(ChildException): # this one is to be deprecated
pass
我想弃用 ChildChildException,考虑到该异常在项目中被使用、引发并与其他异常链接在一起。
最佳答案
您可以使用显示 warning 的装饰器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
app.py:7: DeprecationWarning: ChildChildException is deprecated
更新 :此外,您可以创建自定义警告类并将其传递给 warn 函数:
class ExceptionDeprecationWarning(Warning):
pass
warnings.warn(f"{cls.__name__} is deprecated", ExceptionDeprecationWarning)
关于python - 如何正确弃用 Python 中的自定义异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64660458/