示例工程 11-protocols-generics-overloads

11-protocols-generics-overloads/05-typeis-narrowing/typeis_narrowing.py

python · 1.3 KB

"""演示 TypeIs 的正向/否定收窄;3.12 回退到 TypeGuard。
 
静态差异(TypeGuard 不做否定收窄)由 mypy-typeguard.txt / mypy-typeis.txt 捕获。
"""
 
from __future__ import annotations
 
import sys
from pathlib import Path
 
if sys.version_info >= (3, 13):
    from typing import TypeIs as Narrow
else:
    from typing import TypeGuard as Narrow
 
HERE = Path(__file__).parent
 
 
def is_str_list(value: object) -> Narrow[list[str]]:
    return isinstance(value, list) and all(isinstance(item, str) for item in value)
 
 
def first_upper(value: object) -> str:
    if is_str_list(value):
        return value[0].upper()
    return ""
 
 
def first_error(text: str) -> str:
    for line in text.splitlines():
        if ": error:" in line:
            return line
    return "none"
 
 
def main() -> None:
    guard = (HERE / "mypy-typeguard.txt").read_text(encoding="utf-8")
    typeis = (HERE / "mypy-typeis.txt").read_text(encoding="utf-8")
    print(f"typeguard error: {first_error(guard)}")
    print(f"typeis success: {'Success' in typeis}")
    print(f"runtime narrow: {getattr(Narrow, '__name__', 'unknown')}")
    print(f"list: {first_upper(['ok', 'no'])}")
    print(f"not list: {first_upper(42)!r}")
    print(f"mixed: {first_upper(['ok', 1])!r}")
 
 
if __name__ == "__main__":
    main()