示例工程 10-type-annotations-mypy

10-type-annotations-mypy/04-any-vs-object/any_vs_object.py

python · 1.0 KB

"""演示 Any 关闭检查、object 保留检查。"""
 
from __future__ import annotations
 
from typing import Any
 
 
def leak() -> Any:
    """返回类型写成 Any,调用方拿到「任意类型」。"""
    return "text"
 
 
def takes_int(value: int) -> int:
    return value + 1
 
 
def describe(value: object) -> str:
    """object 必须先用 isinstance 收窄。"""
    if isinstance(value, str):
        return f"str:{value}"
    if isinstance(value, int):
        return f"int:{value}"
    return type(value).__name__
 
 
def object_needs_narrowing(value: object) -> int:
    if isinstance(value, int):
        return value + 1
    return 0
 
 
def main() -> None:
    leaked: int = leak()
    print(f"assigned: {leaked!r}")
    print(f"narrowed: {describe(leaked)}")
    print(f"object helper: {object_needs_narrowing(leaked)}")
    try:
        print(takes_int(leaked))
    except TypeError as exc:
        print(f"runtime error: {exc}")
 
 
if __name__ == "__main__":
    main()