DeprecationWarning属性未在Warnings.py中找到。

huangapple go评论73阅读模式
英文:

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)

huangapple
  • 本文由 发表于 2023年6月19日 19:01:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/76506000.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定