Pyright vs mypy: Choosing the Right Python Type Checker

Pyright vs mypy: Choosing the Right Python Type Checker
Pyright vs mypy: Choosing the Right Python Type Checker

Choosing a static type checker for a Python service is not simply a choice between two commands in a continuous integration pipeline. It determines which errors developers see before running code, how much annotation work is required to expose those errors, and how much effort the team spends maintaining the checking environment. Pyright and mypy both provide useful checks, but they approach some of these problems differently.

The practical decision in 2026 is to establish which checker gives actionable feedback on the code the organization actually owns. For a typed service with conventional dependencies, either may work well. For a framework-heavy application with dynamic model attributes, the available integration may matter more than raw analysis speed. For a shared library, compatibility with consumers may justify checking against both.

What static type checking can and cannot guarantee

The Python type system specification defines the meaning of annotations for static analysis. An annotation describes an intended contract; it does not, by itself, reject invalid data at runtime. Both mypy and Pyright can find incompatible calls and returns when they have sufficient information about the relevant types.

Consider an illustrative service function that accepts a customer identifier as a string and returns a customer record or None. A caller that passes an integer or accesses the record without first handling the missing case should be detected when the relevant interfaces are typed. But a malformed JSON response, a broken database migration or an unexpected permission failure still needs runtime validation and testing.

Type information can also be incomplete. Third-party packages may lack usable annotations or stubs, and explicit Any annotations can prevent meaningful checking. Rather than treating a successful checker run as proof of correctness, identify where untyped information enters the application. Validate external payloads at the boundary and convert them into domain objects before passing them to business logic.

The typing conformance test suite provides a common reference for implementations. Conformance is useful for evaluating language features, but it is not a measure of how many production defects a particular checker will prevent. A repository's use of decorators, generated classes and partial annotations can matter more to the daily experience than broad claims about compliance.

Inference and diagnostic policy

One of the most noticeable differences emerges when developers omit annotations. Microsoft's comparison of Pyright and mypy describes differences in return-type inference and the treatment of values whose types are not known. Pyright can infer return types for functions without explicit return annotations. Mypy generally treats an unannotated return type as Any rather than publishing an inferred return contract, even when other checks are enabled.

This difference does not imply that one checker accepts all bad code that the other rejects. Each checker has configurable diagnostics, and stronger policies can require explicit signatures. Mypy's check_untyped_defs option checks bodies of untyped functions, while requiring annotations is a separate policy choice.

For a team migrating a loosely typed service, richer inference can make errors visible before every function has been annotated. Explicit annotations nevertheless remain valuable for public boundaries. Inference is a description of the current implementation; a written contract can express what callers are allowed to rely on, even after the function is refactored.

Configure the target, not just strict mode

The Pyright configuration guide describes type checking modes, included paths and execution environments. The mypy command-line reference describes its strictness flags and platform targeting. Their strict settings are not interchangeable policy definitions. They enable different collections of checks.

An illustrative starting configuration for a service that runs on Python 3.13 is:

[tool.pyright]
include = ["src", "tests"]
pythonVersion = "3.13"
typeCheckingMode = "standard"

[tool.mypy]
files = ["src", "tests"]
python_version = "3.13"
check_untyped_defs = true
warn_unused_ignores = true

These settings are examples for evaluation, not equivalent diagnostic profiles. A mature codebase can tighten them after inspecting the initial results. For greenfield code, strict checks on new modules may be an affordable default. In a legacy service, requiring immediate cleanup of unrelated files can make the first integration unnecessarily difficult.

Treat the target interpreter version as part of the application contract. A developer running a newer interpreter should not accidentally introduce a typing feature or library API unavailable in production. Also keep the relevant platform and dependency environment consistent. A Linux deployment and a macOS workstation may select different branches of platform-dependent code.

Reproduce the import environment

A checker can report a missing import even though the application runs correctly in a developer's shell. Conversely, an apparently successful analysis may have selected a different dependency installation from the one used by the service. Pyright's import resolution documentation explains how configured search paths and Python environments affect package discovery.

For an illustrative monorepo with a shared package and a worker application, install the shared package into the worker's development environment or explicitly configure the intended source layout. Avoid adding unrelated directories to the analysis path simply to eliminate errors. That can hide a packaging defect that will reappear when a wheel is installed into a clean container.

Keep the checker, the application dependencies and the relevant stub packages in the repository's dependency lock. Verify that a clean runner can import the same packages as the editor environment. With a multi-service repository, evaluate separate configurations where services have different Python targets or dependency versions. A single global environment may silently analyze an interface against the wrong version of its dependency.

When troubleshooting a disagreement, start by inspecting the inferred type at the call site using a temporary reveal_type expression, then inspect where that type originated. A missing stub, an overly broad annotation and an actual checker limitation require different fixes. Do not turn a diagnostic off until the distinction is understood.

Dynamic frameworks and the plugin question

Mypy offers an extension interface for plugins, which can help model behavior that ordinary type annotations cannot conveniently describe. A documented example is django-stubs, which combines type stubs with a mypy plugin for Django. The plugin is particularly relevant when working with the framework's dynamic model and configuration behavior.

A Pyright evaluation can use conventional stubs and annotations, but it should not assume that it executes a mypy plugin. The plugin's contribution to inferred types and diagnostics needs to be evaluated independently. If an application relies on framework-generated attributes and relationships, build a small test corpus from those exact patterns.

There is an operational cost to plugin integration. Check compatibility across framework, checker and stub releases. Where the plugin needs Django settings, ensure the checking environment can initialize the necessary configuration without relying on live services or production credentials. The type-checking job should be reproducible on a clean runner.

For a platform team supporting multiple services, framework-specific needs can justify different checkers for different repositories. A uniform requirement to check typed boundaries is often more useful than a uniform checker executable.

Local feedback and continuous integration

Pyright's feature documentation describes watch mode and incremental updates. Mypy supports incremental checking and a daemon mode that can keep analysis state available between requests. These workflows address similar developer needs, but their resource usage and response times depend on the repository and execution environment.

Do not choose from an old benchmark without reproducing its conditions. Mypy's CLI also documents parallel workers, making comparisons against historical single-process configurations potentially misleading.

For CI, measure from a clean environment as well as with restored caches. For local development, measure the feedback after a small edit, an edit to a widely imported interface and a dependency change. Use the same source tree, interpreter target, dependencies and file scope. Record the actual checker configuration and separate installation time from analysis time.

If the checker is quick but produces diagnostics that developers routinely suppress, the low execution latency may not translate into a useful workflow. Review warnings for correctness, relevance and the effort needed to address them. A slower checker that models an important framework feature accurately can be the more economical choice for that application.

Build a representative evaluation corpus

Use a temporary branch with deliberately small, understandable examples before evaluating the entire repository. Include cases where the expected outcome is an error and cases where valid code should pass. A useful illustrative matrix is:

Pattern Expected behavior
Incompatible parameter type Diagnostic at the invalid call
Optional return value Diagnostic when used without a required check
Protocol-based dependency Accept implementations satisfying the contract
Untyped dependency Expose gaps under the chosen checking policy
Decorator preserving a signature Retain the caller's parameter contract
Framework-generated model field Reflect the documented type where supported

Keep the examples close to real interfaces in the application. For instance, the following deliberately invalid code tests whether a checker preserves an optional return contract:

def find_region(code: str) -> str | None:
    return code if code else None

def normalize_region(code: str) -> str:
    region = find_region(code)
    return region.upper()  # deliberately invalid

The underlying issue is that region may be None. Both tools should diagnose this under configurations that check the code and enforce optional-value safety. The fix is a deliberate domain decision: raise an exception, return an optional result or supply an appropriate fallback. A cast that simply asserts the value is a string does not resolve the runtime problem.

Classify diagnostics on the real repository as actionable defects, annotation work, missing dependency information or suspected checker limitations. Record examples of valid constructs incorrectly rejected as well as invalid constructs missed. A count of errors alone is not a quality measure: one checker may be reporting stricter policy violations while another may be examining a broader scope.

The mypy release news records the 2.4 release in October 2026. This is a reminder to run an evaluation with pinned contemporary versions rather than assume results from an earlier tool generation still apply.

Gradual adoption without permanent blind spots

Mypy's guide for existing codebases recommends gradual introduction of typing. The same general approach can be applied when adopting Pyright. Start with the modules that define shared contracts, such as API clients, configuration parsing and job payloads. Improve the typed interfaces used by many callers before spending time annotating isolated scripts.

Maintain a visible scope for weaker rules and suppressions. When a missing stub is the cause of an error, record the dependency and the required contract rather than disabling import diagnostics across the entire project. Prefer narrow suppressions when an issue cannot immediately be corrected.

Treat untyped interfaces as technical debt that can be reduced over time. New components should follow a written type policy, and existing components can move toward stronger checking when they are modified. This avoids turning an initial compromise into an undocumented exemption.

The checker should run in CI before merging changes, not just in an individual developer's editor. Keep its version and dependency stubs pinned, and make configuration changes reviewable. If an upgrade introduces new diagnostics, distinguish genuine code defects from changes in inference or policy before changing the settings.

Maintain the policy after adoption

For shared packages, keep a small set of typing regression fixtures alongside the runtime tests. A fixture can exercise the accepted shape of a callback, the inferred type of a factory or the return contract of an asynchronous operation. If both checkers are supported, run the same public-interface fixtures against both and document known intentional differences.

An incremental migration can be governed by module ownership. The team responsible for the API package decides how public request and response types are expressed; the team responsible for infrastructure adapters maintains the boundary to external libraries. Central engineering owns the minimum CI policy and the dependency upgrade process. This arrangement is a recommendation rather than evidence of a measured productivity improvement.

For operational planning, track the wall-clock checking time, the number of narrowly scoped suppressions and the number of modules still operating under weaker rules. Examine those measures together rather than optimizing one in isolation. A falling diagnostic count caused by excluded directories is not the same as better type coverage.

A checker upgrade should be a separate change from a large application refactor whenever possible. Review the diagnostics, confirm which changes reflect intended typing semantics and update affected annotations. This makes it easier to identify whether a regression came from the application, a third-party stub or the analysis tool.

Choosing a checker that fits the codebase

For a service with conventional typed dependencies and a strong preference for inference-driven editor feedback, Pyright is a reasonable initial candidate. For a Django application that depends on mypy plugin behavior, mypy deserves an early evaluation. A library with users running both checkers may benefit from testing representative public interfaces against each.

None of these choices requires abandoning runtime checks or tests. Static typing should complement the architecture by making boundaries explicit, exposing inconsistent assumptions and giving developers feedback at the point where a contract changes.

The best choice is the one that supports the team's real interfaces with acceptable noise, predictable configuration and a sustainable maintenance cost. Decide on evidence from the repository rather than a generic ranking, and revisit the decision when the framework, dependency ecosystem or deployment model changes.