Repository navigation
Fix value pattern replacing subject type with value type - #11897
crypt0lith wants to merge 3 commits into
Conversation
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.
🔴 Pyright CLI QA —
|
|
The case flagged by the bot is preexisting on import builtins
class Arbitrary:
pass
def f(subj: Arbitrary) -> Arbitrary:
match subj:
case builtins.str:
pass
return subj |
|
According to mypy_primer, this change doesn't affect type check results on a corpus of open source code. ✅ |
|
On |
d970fc6 to
17c20c9
Compare
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
NeverorNoReturnpattern, that makes the case unreachable, so pyright skips checking its body:When neither type overrides
__eq__or is assignable to the other, the value's type replaces the subject's:Root cause
narrowTypeBasedOnValuePatternnarrows the subject to the type of the pattern's expression, which isn't always one the subject can have:NeverandNoReturn, the expression's type isNever, while the subject is compared against the special form.__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
_SpecialForminstances, so their type doesn't show which subjects they can equal.Fix
Narrow a
NeverorNoReturnvalue pattern against its special form, as subscriptingNeverorNoReturnalready does ingetTypeOfIndexWithBaseType.When neither type overrides
__eq__and neither is assignable to the other:Test
Cases added to
matchValue1.pytest_never_value_patternNeverandNoReturnvalue patterns narrow to the special form and both branches are reachabletest_never_value_pattern_unrelatedNoReturnandNevervalue patterns retain a non-final subject and a_SpecialFormsubject when neither type is assignable to the othertest_unrelated_identity_eq_value_pattern__eq__or is assignable to the other; a non-final subject is retained and a final one is eliminated