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

azm*_*euk 5 python exception deprecation-warning

我写了一个有时会引发异常的库。有一个例外,我想弃用,我想建议人们停止捕捉它们,并在警告消息中提供建议。但是如何使异常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()
Run Code Online (Sandbox Code Playgroud)

用户代码

try:
    mylib.something()
except MyException: # <-- raise a DeprecationWarning here
    pass
Run Code Online (Sandbox Code Playgroud)

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

use*_*ica 9

你不能。发生的逻辑都不except MyException是可定制的。特别是,它完全忽略了诸如__instancecheck__or 之类的东西__subclasscheck__,因此您无法进入确定异常是否与异常类匹配的过程。

当用户尝试使用from yourmodule import MyException或访问您的异常类时,您可以获得的最接近的警告发生yourmodule.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
Run Code Online (Sandbox Code Playgroud)

  • +1这是正确的方法,并且弃用名称实际上是模块“__getattr__”的第一个[PEP中给出的基本原理](https://www.python.org/dev/peps/pep-0562/#rationale)特征。 (2认同)

小智 -1

尝试使用这个:

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()


Run Code Online (Sandbox Code Playgroud)