英文:
DeprecationWarning attribute not found in Warnings.py
问题
我试图在 Python Notebook .ipynb 中使用 Python 3.9.4 运行以下单元格:
import warnings
print(warnings.DeprecationWarning)
结果,我收到以下错误:
> AttributeError Traceback (most recent call
> last) Cell In[1], line 2
> 1 import warnings
> ----> 2 print(warnings.DeprecationWarning)
>
> AttributeError: module 'warnings' has no attribute
> 'DeprecationWarning'
我想要检查 warnings.py 中的 DeprecationWarning 是因为 warnings.warn() 的第二个参数可以是一个警告,可能是 DeprecationWarning:
warnings.warn("THIS IS A WARNING TEXT", warnings.DeprecationWarning)
有任何想法吗?
英文:
I'm trying to run the following cell in a Python Notebook .ipynb using Python 3.9.4:
import warnings
print(warnings.DeprecationWarning)
As a result, I get the following error:
> AttributeError Traceback (most recent call
> last) Cell In[1], line 2
> 1 import warnings
> ----> 2 print(warnings.DeprecationWarning)
>
> AttributeError: module 'warnings' has no attribute
> 'DeprecationWarning'
The reason why I want to check DeprecationWarning in warnings.py is because warnings.warn() takes as second parameter a warning which may be a DeprecationWarning:
warnings.warn("THIS IS A WARNING TEXT", warnings.DeprecationWarning)
Any idea?
答案1
得分: 1
DeprecationWarning
不是 warnings
模块的成员;它是一个内置异常(参见此文档)。
这意味着你可以这样写:
import warnings
def deprecated_function():
warnings.warn("This is a deprecated function", DeprecationWarning)
尝试运行 deprecated_function()
会导致:
.../warningtest.py:4: DeprecationWarning: This is a deprecated function
warnings.warn("This is a deprecated function", DeprecationWarning)
英文:
DeprecationWarning
isn't a member of the warnings
module; it's a built-in exception (see this documentation).
This means you can write:
import warnings
def deprecated_function():
warnings.warn("This is a deprecated function", DeprecationWarning)
Attempts to run deprecated_function()
will result in:
.../warningtest.py:4: DeprecationWarning: This is a deprecated function
warnings.warn("This is a deprecated function", DeprecationWarning)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论