如何正确弃用 Python 中的自定义异常?
How to properly deprecate a custom exception in Python?
我的 Python 项目中有自定义继承异常,我想弃用其中之一。正确的做法是什么?
例外情况:
class SDKException(Exception):
pass
class ChildException(SDKException):
pass
class ChildChildException(ChildException): # this one is to be deprecated
pass
我想弃用 ChildChildException,考虑到该异常在项目中被使用、引发并与其他异常链接。
您可以使用装饰器,它在异常的每个实例化上显示 warning DeprecationWarning
类别 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
更新:
此外,您可以创建自定义警告 class 并将其传递给警告函数:
class ExceptionDeprecationWarning(Warning):
pass
warnings.warn(f"{cls.__name__} is deprecated", ExceptionDeprecationWarning)
我的 Python 项目中有自定义继承异常,我想弃用其中之一。正确的做法是什么?
例外情况:
class SDKException(Exception):
pass
class ChildException(SDKException):
pass
class ChildChildException(ChildException): # this one is to be deprecated
pass
我想弃用 ChildChildException,考虑到该异常在项目中被使用、引发并与其他异常链接。
您可以使用装饰器,它在异常的每个实例化上显示 warning DeprecationWarning
类别 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
更新: 此外,您可以创建自定义警告 class 并将其传递给警告函数:
class ExceptionDeprecationWarning(Warning):
pass
warnings.warn(f"{cls.__name__} is deprecated", ExceptionDeprecationWarning)