アノテーションの遅延評価
#Python3.14の新機能
評価タイミングの変更
アノテーションの評価が遅延されるようになりました。実行時にその情報が実際に必要になったときに評価されます。
前方参照の問題解消
遅延評価になったため、文字列化や__future__インポートといった特別な措置なしに、型ヒントを記述できるようになりました。
code: sample.py
from annotationlib import Format, get_annotations
def func(arg: Undefined): # type: ignore # noqa: F821
pass
def run():
""">>> run()
結果
----
- Format.VALUE: Error occurred: name 'Undefined' is not defined
- Format.FORWARDREF: {'arg': ForwardRef('Undefined', owner=<function func at 0x1024fc460>)}
- Format.STRING: {'arg': 'Undefined'}
"""
try:
# 評価されるタイミングでNameErrorになる
result = get_annotations(func, format=Format.VALUE)
except NameError as e:
print(f"Error occurred: {e}")
result = get_annotations(func, format=Format.FORWARDREF)
print(result)
result = get_annotations(func, format=Format.STRING)
print(result)
#Python #Python3.14