Skip to content

Fix value pattern replacing subject type with value type - #11897

Open
crypt0lith wants to merge 3 commits into
microsoft:mainfrom
crypt0lith:fix/never-value-pattern
Open

crypt0lith wants to merge 3 commits into
microsoft:mainfrom
crypt0lith:fix/never-value-pattern

Conversation

@crypt0lith

@crypt0lith crypt0lith commented Oct 20, 2026 •

Copy link
Copy Markdown
Contributor

Summary

A value pattern narrows the matched subject to the type of the pattern's expression, which isn't always a type the subject can have. For a Never or NoReturn pattern, that makes the case unreachable, so pyright skips checking its body:

# pyright: reportUnreachable=true
import typing

def f(subj: object):
    match subj:
        case typing.Never:
            reveal_type(subj)
:7:13 - error: Type analysis indicates code is unreachable (reportUnreachable)

When neither type overrides __eq__ or is assignable to the other, the value's type replaces the subject's:

import builtins

class Arbitrary:
    pass

def f(subj: Arbitrary) -> Arbitrary:
    match subj:
        case builtins.str:
            pass
    return subj
:10:12 - error: Type "type[str] | Arbitrary" is not assignable to return type "Arbitrary"
  Type "type[str] | Arbitrary" is not assignable to type "Arbitrary"
    Type "type[str]" is not assignable to type "Arbitrary" (reportReturnType)

Root cause

narrowTypeBasedOnValuePattern narrows the subject to the type of the pattern's expression, which isn't always one the subject can have:

  • For Never and NoReturn, the expression's type is Never, while the subject is compared against the special form.
  • When neither the subject nor the value overrides __eq__ and neither type is assignable to the other, a non-final subject can match only through a subclass that overrides __eq__, and keeps its own type. A subject that can't be subclassed can't match at all.

Special forms are modeled as their own classes rather than as _SpecialForm instances, so their type doesn't show which subjects they can equal.

Fix

Narrow a Never or NoReturn value pattern against its special form, as subscripting Never or NoReturn already does in getTypeOfIndexWithBaseType.

When neither type overrides __eq__ and neither is assignable to the other:

  • If the subject is a final class or an enum with members and the value is not a special form, eliminate the subject.
  • Otherwise, retain the subject.

Test

Cases added to matchValue1.py
Case Expected Description
test_never_value_pattern Never and NoReturn value patterns narrow to the special form and both branches are reachable
test_never_value_pattern_unrelated NoReturn and Never value patterns retain a non-final subject and a _SpecialForm subject when neither type is assignable to the other
test_unrelated_identity_eq_value_pattern Neither type overrides __eq__ or is assignable to the other; a non-final subject is retained and a final one is eliminated

A value pattern of Never or NoReturn evaluates to the Never type,
so narrowing always produces Never and pyright treats the case as
unreachable, though at runtime it compares the subject against the
special form object. Narrow against the special form instead.
@heejaechang

Copy link
Copy Markdown
Collaborator

🔴 Pyright CLI QA — b766b594 — verdict: red

Automated CLI checks compared this change with its base revision.
13 focused check(s) completed.

Needs review: reportReturnType newly reported

The PR reports reportReturnType for this example; the base does not. Is this change intended?

Reproduction and observed results

Create these files in an empty directory:

main.py

import typing

class Token:
    pass

def identity(value: Token) -> Token:
    match value:
        case typing.NoReturn:
            pass
    return value

pyrightconfig.json

{
  "include": [
    "main.py"
  ],
  "pythonVersion": "3.13",
  "typeCheckingMode": "standard"
}

From that directory, run each built Pyright revision:

node <pyright-cli-entrypoint> --outputjson -p .

Base e80c920278f15973001d1a33414b0a7cafdc5ed2

{
  "exit_code": 0,
  "diagnostics": []
}

PR b766b594c13a9437f96c2dd398f667175685d102

{
  "exit_code": 1,
  "diagnostics": [
    {
      "file": "main.py",
      "severity": "error",
      "rule": "reportReturnType",
      "message": "Type \"type[NoReturn] | Token\" is not assignable to return type \"Token\"\n  Type \"type[NoReturn] | Token\" is not assignable to type \"Token\"\n    Type \"type[NoReturn]\" is not assignable to type \"Token\"",
      "range": {
        "start": [
          9,
          11
        ],
        "end": [
          9,
          16
        ]
      }
    }
  ]
}

Diagnostic ranges use zero-based line and character positions.

@crypt0lith

Copy link
Copy Markdown
Contributor Author

The case flagged by the bot is preexisting on main and not exclusive to Never or NoReturn:

import builtins

class Arbitrary:
    pass

def f(subj: Arbitrary) -> Arbitrary:
    match subj:
        case builtins.str:
            pass
    return subj
:10:12 - error: Type "type[str] | Arbitrary" is not assignable to return type "Arbitrary"
  Type "type[str] | Arbitrary" is not assignable to type "Arbitrary"
    Type "type[str]" is not assignable to type "Arbitrary" (reportReturnType)

@crypt0lith crypt0lith changed the title Fix match value patterns of Never and NoReturn treated as unreachable Fix value pattern replacing subject type with value type Oct 20, 2026
@github-actions

Copy link
Copy Markdown
Contributor

According to mypy_primer, this change doesn't affect type check results on a corpus of open source code. ✅

@bschnurr

Copy link
Copy Markdown
Member

On d970fc6f, the focused MatchValue1 test passes locally. The current Ubuntu validation failure is not in that test: mypyPrimerAnalysis.test.ts fails its compiled-workflow/compiler-resolution-lock SHA check (expected 5e508589, received 406c7719; job). Please reconcile that lock/runtime mismatch and rerun validation. I have not independently verified the other platform failures or the full suite.

@crypt0lith
crypt0lith force-pushed the fix/never-value-pattern branch from d970fc6 to 17c20c9 Compare November 21, 2026 08:05

This branch has not been deployed

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants