示例工程 11-protocols-generics-overloads

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

python · 1.2 KB

"""重新生成 mypy-typeguard.txt / mypy-typeis.txt(需要 mypy 支持 --python-version 3.13)。"""
 
from __future__ import annotations
 
import shutil
import subprocess
import sys
import tempfile
from pathlib import Path
 
HERE = Path(__file__).parent
 
 
def run_fixture(fixture: str) -> str:
    filename = fixture.removesuffix(".txt")
    with tempfile.TemporaryDirectory() as tmp:
        shutil.copyfile(HERE / fixture, Path(tmp) / filename)
        proc = subprocess.run(
            [
                sys.executable,
                "-m",
                "mypy",
                "--strict",
                "--python-version",
                "3.13",
                filename,
            ],
            cwd=tmp,
            capture_output=True,
            text=True,
            check=False,
        )
    return proc.stdout + proc.stderr
 
 
def main() -> None:
    for fixture, output in (
        ("typeguard_case.py.txt", "mypy-typeguard.txt"),
        ("typeis_case.py.txt", "mypy-typeis.txt"),
    ):
        text = run_fixture(fixture)
        (HERE / output).write_text(text, encoding="utf-8")
        print(f"=== {output} ===")
        print(text, end="")
 
 
if __name__ == "__main__":
    main()