如何在用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()

最新更新