# 注意:下面的内容都需要 Python 3.13 或更新版本。
# 示例运行环境是 Python 3.12,其中还没有这些功能。
import warnings
# *** 以前 ***
# 过去警告要在函数体里手动发出,文档字符串再用文字重复一遍,
# 而检查器和编辑器对此一无所知
def old_style(text):
"""Deprecated, use new_style instead."""
warnings.warn("old_style is deprecated, use new_style",
DeprecationWarning, stacklevel=2)
return text.upper()
# *** 在 3.13 版本中 ***
from warnings import deprecated
@deprecated("use new_style instead")
def old_style_new(text):
return text.upper()
@deprecated("Shape is replaced by Figure")
class Shape:
pass
class Figure:
@deprecated("use area() instead")
def size(self):
return 0
def new_style(text):
return text.upper()
# 装饰器两件事一次完成:名称被使用时发出 DeprecationWarning,
# 并为检查器和编辑器做标记,
# 它们会在调用处直接给该名称加删除线
with warnings.catch_warnings(record=True) as caught:
warnings.simplefilter("always")
print(old_style("a"), old_style_new("b"), new_style("c"))
Figure().size()
for entry in caught:
print(entry.category.__name__ + ":", entry.message)