示例工程 10-type-annotations-mypy
10-type-annotations-mypy/05-reveal-type/reveal_type.py
"""演示 reveal_type:mypy 打印推断类型;运行时通过 TYPE_CHECKING 跳过。"""
from __future__ import annotations
from pathlib import Path
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from typing import reveal_type
HERE = Path(__file__).parent
def add(a: int, b: int) -> int:
if TYPE_CHECKING:
reveal_type(a)
return a + b
def maybe(flag: bool) -> int | None:
if TYPE_CHECKING:
reveal_type(flag)
return 1 if flag else None
def mypy_notes() -> list[str]:
text = (HERE / "mypy-output.txt").read_text(encoding="utf-8")
return [line for line in text.splitlines() if "Revealed type" in line]
def main() -> None:
print("mypy notes:")
for note in mypy_notes():
print(f" {note}")
value = add(1, 2)
if TYPE_CHECKING:
reveal_type(value)
print(f"value: {value}")
print(f"maybe: {maybe(True)}")
if __name__ == "__main__":
main()