Christian Ledermann: Migrate From mypy To ty And pyrefly
This guide details the migration of the fastkml Python package from mypy to ty and pyrefly. It emphasizes running both ty and pyrefly concurrently, as they catch different subsets of errors, providing a more complete picture than a single checker. The process begins with establishing a baseline error count for both tools before any code changes.The key to efficient migration lies in identifying and addressing systemic root causes, often related to optional C-extension backends, rather than fixing errors file by file. Genuine bugs exposed by the tools, especially concerning Optional/union narrowing and positional-only stubs, should be rectified. Noise from test files, specifically "constructed-then-accessed-without-narrowing" issues, should be bulk-suppressed using scoped rules.The guide advises turning on strict presets and then promoting specific rules, while explicitly cutting those that cause excessive mechanical churn. Verification involves ensuring both tools report no errors, the full test suite passes, and linters are clean. Before migration, thoroughly analyze the existing mypy configuration to understand the strictness bar ty and pyrefly need to match or exceed.Inventorying the mypy config involves mapping its settings to their rough ty/pyrefly equivalents and removing stale per-module disable error code overrides. After installing ty and pyrefly, obtaining a baseline error count categorized by error kind and then by file is crucial; the latter usually reveals systemic causes. If a partial migration exists with broad suppressions, it should be treated as a red flag, and suppressions removed to see the true baseline.The highest leverage move is fixing architectural mismatches that both checkers flag. A common pattern involves optional backends handled via try/except imports, where the fix is often an if TYPE_CHECKING: block to allow type checkers to see the richer backend's stubs. Pitfalls include the non-portability of # type: ignore[code] comments, pyrefly's TOML key casing issues, the fragility of pyrefly's array-of-tables syntax against interleaving, and the inability of a Protocol to be directly assigned to a concrete class parameter. Careful verification of tool behavior and configuration is essential throughout the process.
if TYPE_CHECKING:block to allow type checkers to see the richer backend's stubs. Pitfalls include the non-portability of# type: ignore[code]comments, pyrefly's TOML key casing issues, the fragility of pyrefly's array-of-tables syntax against interleaving, and the inability of a Protocol to be directly assigned to a concrete class parameter. Careful verification of tool behavior and configuration is essential throughout the process.