access-annotations-from-class-dict (RUF063)
此规则不稳定且处于预览状态。使用需要 --preview
标志。
作用
检查在 Python 3.10+ 和 Python < 3.10 中使用 foo.__dict__.get("__annotations__")
或 foo.__dict__["__annotations__"]
的情况,当启用了 typing-extensions 时。
为什么这不好?
从 Python 3.14 开始,直接通过 foo.__dict__.get("__annotations__")
或 foo.__dict__["__annotations__"]
访问 __annotations__
只有在类定义在 from __future__ import annotations
下时才会返回注解。
因此,最好使用专用的库函数,例如 annotationlib.get_annotations
(Python 3.14+)、inspect.get_annotations
(Python 3.10+) 或 typing_extensions.get_annotations
(对于 Python < 3.10 如果 typing-extensions 可用)。
使用这些函数的好处包括
- 避免未文档化的内部机制:它们提供了稳定的公共 API,不同于直接
__dict__
访问,后者依赖于实现细节。 - 前向兼容性:它们旨在处理 Python 各版本中注解系统的变化,确保您的代码保持健壮(例如,正确处理上面提到的 Python 3.14 行为)。
有关替代方案,请参阅Python 注解最佳实践。
示例
在 Python 3.14+ 上,请改用
在 Python 3.10+ 上,请改用
在安装了 typing-extensions 的 Python < 3.10 上,请改用
修复安全性
目前没有为此规则提供自动修复。
修复可用性
目前没有为此规则提供自动修复。