注解默认延迟求值
注解不再在定义时立即求值,annotationlib 可按值、前向引用或字符串读取注解。
怎么用声明晚于函数定义的类型更自然;框架可按需求选择读取格式。
旧版做法前向引用用字符串,如 user: 'User',或启用 future annotations。
注意事项读取 VALUE 格式时仍会求值,未定义名称可能报错;保留 future annotations 的代码需要单独核对。
官方依据 ↗ · 最低版本 3.14 · 核对于 2026-10-06
from annotationlib import Format, get_annotations
def greet(user: User) -> str:
return user.name
class User:
name = "Ada"
print(get_annotations(greet, format=Format.STRING)){'user': 'User', 'return': 'str'}