在使用python捕获异常时如何引发DeprecationWarning?

问题描述

我写了一个有时会引发异常的库。我想弃用一个例外,我想建议人们停止抓住他们,并在警告消息中提供建议。但是,如何在捕获到异常时发出DeprecationWarning

库代码

import warnings

class MyException(ValueError):
    ...
    warnings.warn(
        "MyException is deprecated and will soon be replaced by `ValueError`.",DeprecationWarning,stacklevel=2,)
    ...

def something():
    raise MyException()

用户代码

try:
    mylib.something()
except MyException: # <-- raise a DeprecationWarning here
    pass

如何修改MyException以实现这一目标?

解决方法

不能。 except MyException中发生的逻辑均不可自定义。特别是,它完全忽略了__instancecheck____subclasscheck__之类的东西,因此您无法参与确定异常是否与异常类匹配的过程。

当用户尝试使用from yourmodule import MyExceptionyourmodule.MyException访问您的异常类时,发生的警告最接近。您可以使用模块__getattr__

class MyException(ValueError):
    ...

# access _MyException instead of MyException to avoid warning
# useful if other submodules of a package need to use this exception
# also use _MyException within this file - module __getattr__ won't apply.
_MyException = MyException
del MyException

def __getattr__(name):
    if name == 'MyException':
        # issue warning
        return _MyException
    raise AttributeError
,

尝试使用此:

import warnings


class MyOtherException(Exception):
    pass


class MyException(MyOtherException):
    def __init__(self):
        warnings.warn(
            "MyException is deprecated and will soon be replaced by `MyOtherException`.",DeprecationWarning,stacklevel=2,)


if __name__ == "__main__":
    try:
        mylib.something()
    except Exception:
        raise MyException()


相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...