[英]How to raise a DeprecationWarning when catching an exception with python?
I wrote a library that sometimes raises exceptions.我写了一个有时会引发异常的库。 There is an exception that I want to deprecate, and I would like to advise people to stop catching them, and provide advises in the warning message.
有一个例外,我想弃用,我想建议人们停止捕捉它们,并在警告消息中提供建议。 But how to make an exception emit a
DeprecationWarning
when catched?但是如何使异常在捕获时发出
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
How can I modify MyException
to achieve this?如何修改
MyException
以实现此目的?
You can't.你不能。 None of the logic that occurs in
except MyException
is customizable. except MyException
,发生的所有逻辑except MyException
是可定制的。 Particularly, it completely ignores things like __instancecheck__
or __subclasscheck__
, so you can't hook into the process of determining whether an exception matches an exception class.特别是,它完全忽略了
__instancecheck__
或__subclasscheck__
类的东西,因此您无法进入确定异常是否与异常类匹配的过程。
The closest you can get is having the warning happen when a user tries to access your exception class with from yourmodule import MyException
or yourmodule.MyException
.当用户尝试使用
from yourmodule import MyException
或yourmodule.MyException
访问您的异常类时,您可以获得的最接近的警告发生。 You can do that with a module __getattr__
:您可以使用模块
__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
Try using this:尝试使用这个:
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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.