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

标签 python exception deprecated

我的 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/

相关文章:

python - 避免插入 SQL 表中已有的记录

PHP DRY 抛出 InvalidArgumentException

python - 打印与写入期间 IOError 的可能性

ios - "deprecated"在iOS中的真正含义是什么

visual-studio-2017 - 如何在 Visual Studio C++17 中恢复 auto_ptr

r - R 包中的数据弃用

Python 多行 JSON 和变量

python - 如何使用bulkloader上传日期?

python - 关于Python中__init__的正确使用

C++ 异常访问冲突