示例工程 10-type-annotations-mypy

10-type-annotations-mypy/01-annotations-are-metadata/annotations_are_metadata.py

python · 1.0 KB

"""演示注解只是 __annotations__ 里的对象:运行时既不检查也不转换。"""
 
from typing import cast
 
 
def add(a: int, b: int) -> int:
    """声明返回 int,但运行时由操作数决定。"""
    return a + b
 
 
def optional(value: int | None = None) -> list[int]:
    """注解在 def 执行时求值,存进函数对象的 __annotations__。"""
    return [] if value is None else [value]
 
 
def main() -> None:
    annotations = add.__annotations__
    print(f"raw annotations: {annotations}")
    print(f"annotation values: {[type(item).__name__ for item in annotations.values()]}")
    optional_annotations = optional.__annotations__
    print(f"optional annotations: {optional_annotations}")
    print(f"optional value type: {type(optional_annotations['value']).__name__}")
    print(f"optional return type: {type(optional_annotations['return']).__name__}")
    result = add(cast(int, "1"), cast(int, "2"))
    print(f"runtime result: {result!r}")
    print(f"runtime type: {type(result).__name__}")
 
 
if __name__ == "__main__":
    main()