示例工程 10-type-annotations-mypy

10-type-annotations-mypy/01-annotations-are-metadata/README.md

markdown · 0.8 KB

# 01 · annotations-are-metadata
 
**演示**:注解保存在 `__annotations__` 里,只是对象;`cast` 能骗过类型检查器,运行时不检查也不转换参数。
**运行**:
 
```sh
uv run python examples/10-type-annotations-mypy/01-annotations-are-metadata/annotations_are_metadata.py
```
 
**预期输出**(3.12.9):
 
```text
raw annotations: {'a': <class 'int'>, 'b': <class 'int'>, 'return': <class 'int'>}
annotation values: ['type', 'type', 'type']
optional annotations: {'value': int | None, 'return': list[int]}
optional value type: UnionType
optional return type: GenericAlias
runtime result: '12'
runtime type: str
```
 
**依赖**:仅标准库。
**注意**:`int | None` 的类型是 `types.UnionType`,`list[int]` 的类型是 `types.GenericAlias`,它们都是普通对象,可以被打印、比较、放进字典。