我编写了一个库,有时会触发异常。我想要废弃其中的一种异常,并建议人们停止捕获它们,在警告信息中提供建议。但是如何让一个异常在被捕获时发出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
已经被弃用,但是没有好的替代方案供用户使用。 - user2357112__getattr__
模块。 - wim