Skip to content

Add pyright check #456

Closed
Closed

Description

@guicho271828

pyright is a static type checker written by Microsoft (and they have a really good verification team)
it is written in typescript but there is a python wrapper and a pre-commit hook.

There are certain cases that mypy does not check strictly while pyright does.
For example, the following code passes mypy while not in pyright

from typing_extensions import TypeVar

T = TypeVar("T")
S = TypeVar("S", default=int)
U = TypeVar("U")

def fn(x: T, y: S, z: U):
    pass
(mellea) [masataro mellea]$ pyright test.py
/home/masataro/repos/LLM/mellea/test.py
  /home/masataro/repos/LLM/mellea/test.py:12:5 - error: "U" cannot appear after "S" in type parameter list because it has no default type (reportGeneralTypeIssues)
  /home/masataro/repos/LLM/mellea/test.py:12:11 - warning: TypeVar "T" appears only once in generic function signature
    Use "object" instead (reportInvalidTypeVarUse)
  /home/masataro/repos/LLM/mellea/test.py:12:22 - warning: TypeVar "U" appears only once in generic function signature
    Use "object" instead (reportInvalidTypeVarUse)
1 error, 2 warnings, 0 informations

(mellea) [masataro mellea]$ mypy test.py
Success: no issues found in 1 source file

Thsi is because it makes sure that no type parameter with a default is followed by a type parameter without a default.
Type variables are applied to the defined class in the order in which they first appear in any generic base classes, thus
fn is instantiated as fn[T, S, U] where U violates this rule.
This was originally specified in PEP 696 (Type Defaults for Type Parameters) and
is now part of official spec https://typing.python.org/en/latest/spec/generics.html#type-parameter-defaults .

The annoying thing is that VSCode suggests users to enable pylance/pyright , and reports a bunch of similar errors to the user that are not detected by mypy.

Activity

  1. changed the title [-]Replace mypy check with pyright check[/-] [+]Add pyright check[/+] on Feb 11, 2026
  2. psschwei commented on Feb 11, 2026

    @psschwei
    Contributor

    Do we need to keep both? Or could we remove mypy in favor of pyright?

  3. guicho271828 commented on Feb 12, 2026

    @guicho271828
    ContributorAuthor

    Now to think of it ....
    Reading a discussion like this, I feel pyright will further slow down the local development.

    So far I am already heavily annoyed by the fact that each time I make a commit, even a temporary commit, it forces me to type check and lint everything. Basically, the current set up in this repo prohibits a typical git workflow where I make multiple branches to experiment, make temporary commits, push it to remote so that I can work from multiple devices (from laptop, compute server login node, and so on), make sure they work, polish it by rewriting/squashing them, and submit a PR for merging.

    It makes sense to protect the integrity of the main branch with mypy/pyright and therefore to check every PR with mypy, linter, and so on. It does not make sense to disallow making a temporary commit. (In addition, I can't even make a commit in magit because magit calls git outside the conda environment, which does not have uv and mypy. Every time I have to go back to the terminal to make a commit only in this project).

  4. psschwei commented on Feb 12, 2026

    @psschwei
    Contributor

    magit

    🎉

    I am already heavily annoyed by the fact that each time I make a commit, even a temporary commit, it forces me to type check and lint everything. Basically, the current set up in this repo prohibits a typical git workflow where I make multiple branches to experiment, make temporary commits, push it to remote so that I can work from multiple devices (from laptop, compute server login node, and so on), make sure they work, polish it by rewriting/squashing them, and submit a PR for merging

    I think this might be worth revisiting (I too feel this pain). Maybe we should open a discussion?

  5. planetf1 commented on Mar 17, 2026

    @planetf1
    Contributor

    It's possible to bypass commits with a --no-verify. I do use this sometimes - especially when experimenting/early stage or just to keep things 'safe' .

    But in general having a pre-commit I feel is good - it can save the time from waiting to see a PR fail CI, and when coding with AI agents this forced-check (without override) encourages them to correct, regardless of any specific guidance.

    Rigour/tool quality is related -- two newer projects are Pyrefly (meta) and ty (astral) - but with different coverage/maturity. I do find mypy frequently painful as a specific checker - it's slow, seems to often trip up/need cache resetting

  6. planetf1 commented on Mar 17, 2026

    @planetf1
    Contributor

    ty:

    ➜ time ty check ./test.py
    error[[invalid-type-variable-default](https://ty.dev/rules#invalid-type-variable-default)]: Type parameters without defaults cannot follow type parameters with defaults
     --> test.py:8:17
      |
    8 | def fn(x: T, y: S, z: U):
      |                 -     ^ Type variable `U` does not have a default
      |                 |
      |                 Earlier TypeVar `S` has a default
    9 |     pass
      |
     ::: test.py:4:1
      |
    3 | T = TypeVar("T")
    4 | S = TypeVar("S", default=int)
      | ----------------------------- `S` defined here
    5 | U = TypeVar("U")
      | ---------------- `U` defined here
      |
    info: rule `invalid-type-variable-default` is enabled by default
    
    Found 1 diagnostic
    ty check ./test.py  0.03s user 0.02s system 78% cpu 0.052 total
    ➜ time pyrefly check ./test.py
    ERROR Type parameter `U` without a default cannot follow type parameter `S` with a default [invalid-type-var]
     --> test.py:8:1
      |
    8 | / def fn(x: T, y: S, z: U):
    9 | |     pass
      | |________^
      |
     INFO 1 error
    pyrefly check ./test.py  0.13s user 0.07s system 70% cpu 0.283 total
  7. psschwei commented on Mar 17, 2026

    @psschwei
    Contributor

    My personal preference is to not block committing and let the CI catch failures (if folks are pushing directly to main then it's a different story). But it's not super important, whatever most folks want is fine.

  8. planetf1 commented on Mar 26, 2026

    @planetf1
    Contributor

    I did a comparison of pyright, ty, mypy- here's a summarised report after getting tests run across all of these, with some analysis and tightning of the checks:


    Type Checker Comparison: What Each Tool Finds in mellea/ Core

    Raw Numbers

    mypy (current) mypy (tightened¹) ty pyright
    Real bugs found 0 ~52 ~76 ~30
    Stale # type: ignore 0 215 121 0
    False positives 0 0 37 ~52
    Total diagnostics 1 ~267 236 126
    Wall time 3.6s cached ~same 6.0s 16s

    ¹ check_untyped_defs = true + warn_unused_ignores = true

    False Positive Patterns (Same Root Cause Across Tools)

    Pattern ty pyright Root Cause
    MelleaBasePayload attrs missing 19 errors 20 errors Conditional TYPE_CHECKING base class in plugin system
    Pydantic model_fields_set / model_extra 4 errors 8 errors Pydantic metaclass-injected attrs not visible statically
    cpex try/except import → possibly unbound 0 52 errors Names defined in try block, guarded by _HAS_PLUGIN_FRAMEWORK at runtime
    Callable.__name__ 8 errors 3 errors Callable typed as (...) -> Unknown, no __name__ on that protocol
    ~AlwaysFalsy after guard 6 errors 0 ty-specific narrowing limitation

    Both tools trip on the same optional-dependency patterns. Neither is clean on this codebase without suppression.

    Unique Findings — What Each Tool Catches Alone

    Finding mypy ty pyright Severity
    Stale # type: ignore comments (121-215) ✅² ✅ — Low (cleanup)
    invalid-argument-type (24 in core) ~14² ✅ ~6 High
    invalid-return-type (7 in core) partial² ✅ — High
    invalid-assignment (7 in core) ~3² ✅ — Medium
    Possibly unbound variable (4 real bugs) — — ✅ High (runtime UnboundLocalError)
    reportRedeclaration (2) — — ✅ Medium

    ² Only with check_untyped_defs = true

    The 4 Bugs Only pyright Finds

    dict_id and doc_roles used in except/else blocks after assignment in try — if the try fails before the assignment, these are unbound at runtime. Neither mypy nor ty detects this. Files:

    • mellea/formatters/granite/granite3/output.py:266
    • mellea/formatters/granite/granite3/granite32/output.py:481
    • mellea/formatters/granite/granite3/granite33/output.py:381
    • mellea/formatters/granite/intrinsics/input.py:144

    These should be fixed regardless of which tool we adopt.

    Recommendation

    Don't pick one tool. Use two, for different jobs.

    Purpose Tool Why
    CI gate mypy (tightened) Already integrated. Adding check_untyped_defs = true and warn_unused_ignores = true goes from 1 → ~267 findings with zero false positives. Stable, no new infra.
    Local dev ty Faster, catches ~30 real bugs mypy misses even when tightened, built-in LSP, zero config beyond pyproject.toml. Suppress the 37 false positives via overrides.
    One-off audit pyright Run periodically to catch PossiblyUnbound and Redeclaration bugs that neither mypy nor ty finds. Not worth adding to CI (Node.js dep, 41% noise rate).

    Immediate Actions

    1. Tighten mypy config — add two lines to pyproject.toml:
      [tool.mypy]
      check_untyped_defs = true
      warn_unused_ignores = true
    2. Fix the 4 dict_id/doc_roles unbound bugs — real runtime risk
    3. Add [tool.ty] config — for individual local use
    4. Clean up stale # type: ignore comments — mechanical, safe, reduces noise for all tools

    So in summary mypy does seem to remain probably the best CI checker -- but we're missing things and tightning that up would be beneficial.

    But ty can be useful as a dev tool and it may be friendlier to use in pre-commit -- if we continue to have anything there. If we do want that, this was the config I ended up with:

    # pyproject.toml — add alongside existing [tool.mypy]
    
    # -----------------------------
    # ty - Type Checking
    # -----------------------------
    
    [tool.ty.environment]
    python-version = "3.12"
    
    [tool.ty.rules]
    empty-body = "ignore"                    # Abstract methods, protocol stubs (62 in docs/tests)
    unused-type-ignore-comment = "warn"      # Keep as warnings — drive cleanup, don't block
    
    [tool.ty.src]
    exclude = ["scratchpad/", "tmp/"]
    
    [tool.ty.terminal]
    output-format = "full"
    error-on-warning = false
    
    # --- Optional dependency imports ---
    
    [[tool.ty.overrides]]
    include = ["docs/**"]
    [tool.ty.overrides.rules]
    unresolved-import = "ignore"
    
    [[tool.ty.overrides]]
    include = ["mellea/backends/vllm.py"]
    [tool.ty.overrides.rules]
    unresolved-import = "ignore"
    
    [[tool.ty.overrides]]
    include = ["docs/**", "cli/decompose/**"]
    [tool.ty.overrides.rules]
    unresolved-import = "ignore"
    
    
    # --- Known ty false positives (conditional TYPE_CHECKING base class, Pydantic metaclass) ---
    
    [[tool.ty.overrides]]
    include = [
        "mellea/plugins/base.py",           # MelleaBasePayload conditional base (19 errors) — ty#1553
        "mellea/core/backend.py",           # Downstream MelleaBasePayload attr access
        "mellea/stdlib/session.py",         # Downstream MelleaBasePayload attr access
        "mellea/plugins/decorators.py",     # Downstream MelleaBasePayload attr access
        "mellea/plugins/registry.py",       # Downstream MelleaBasePayload attr access
        "mellea/plugins/types.py",          # Downstream MelleaBasePayload attr access
    ]
    [tool.ty.overrides.rules]
    unresolved-attribute = "warn"            # Demote — real issues still visible as warnings
    
    [[tool.ty.overrides]]
    include = ["mellea/formatters/granite/base/types.py"]  # Pydantic model_fields_set/model_extra (4 errors)
    [tool.ty.overrides.rules]
    unresolved-attribute = "warn"
    
    [[tool.ty.overrides]]
    include = ["mellea/backends/tools.py"]   # Callable.__name__ (8 errors)
    [tool.ty.overrides.rules]
    unresolved-attribute = "warn"
    
    [[tool.ty.overrides]]
    include = ["mellea/formatters/granite/granite3/input.py"]  # ~AlwaysFalsy narrowing (6 errors)
    [tool.ty.overrides.rules]
    unresolved-attribute = "warn"

    That in itself shows there are some very specific pain points in specific files

    Just maybe, and until ty is more mature, sticking with mypy but tightning up the rules & cleaning up those missing type issues is the most pragmatic step, rather than going to ty or pyright (which is painful due to nodejs)

  9. psschwei commented on May 12, 2026

    @psschwei
    Contributor

    we're going to stay with status quo for now

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions