-
Notifications
You must be signed in to change notification settings - Fork 1.8k
Fix type narrowing for class equality comparisons #11607
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -373,6 +373,22 @@ export function getTypeNarrowingCallback( | |
| }; | ||
| }; | ||
| } | ||
|
|
||
| // Look for X == <class> or X != <class>. | ||
| if (isInstantiableClass(rightType)) { | ||
| return (type: Type) => { | ||
| return { | ||
| type: narrowTypeForClassComparison( | ||
| evaluator, | ||
| type, | ||
| rightType, | ||
| adjIsPositiveTest, | ||
| /* isIsOperator */ false | ||
| ), | ||
| isIncomplete: !!rightTypeResult.isIncomplete, | ||
| }; | ||
| }; | ||
| } | ||
| } | ||
|
|
||
| // Look for X[<literal>] == <literal> or X[<literal>] != <literal> | ||
|
|
@@ -2585,17 +2601,47 @@ function narrowTypeForTypeIs(evaluator: TypeEvaluator, type: Type, classTypes: C | |
| return combineTypes(typesToCombine); | ||
| } | ||
|
|
||
| function hasCustomEqualityMetaclass(classType: ClassType): boolean { | ||
| const metaclass = classType.shared.effectiveMetaclass; | ||
| if (metaclass && isClass(metaclass)) { | ||
| if ( | ||
| lookUpClassMember( | ||
| metaclass, | ||
| '__eq__', | ||
| MemberAccessFlags.SkipTypeBaseClass | MemberAccessFlags.SkipObjectBaseClass | ||
| ) || | ||
| lookUpClassMember( | ||
| metaclass, | ||
| '__ne__', | ||
| MemberAccessFlags.SkipTypeBaseClass | MemberAccessFlags.SkipObjectBaseClass | ||
| ) | ||
| ) { | ||
| return true; | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Checking only the declared |
||
| } | ||
| } | ||
| return false; | ||
| } | ||
|
|
||
| // Attempts to narrow a type based on a comparison with a class using "is" or | ||
| // "is not". This pattern is sometimes used for sentinels. | ||
| // "is not", or "==" or "!=". | ||
| function narrowTypeForClassComparison( | ||
| evaluator: TypeEvaluator, | ||
| referenceType: Type, | ||
| classType: ClassType, | ||
| isPositiveTest: boolean | ||
| isPositiveTest: boolean, | ||
| isIsOperator = true | ||
| ): Type { | ||
| if (!isIsOperator && hasCustomEqualityMetaclass(classType)) { | ||
| return referenceType; | ||
| } | ||
|
|
||
| return mapSubtypes(referenceType, (subtype) => { | ||
| let concreteSubtype = evaluator.makeTopLevelTypeVarsConcrete(subtype); | ||
|
|
||
| if (!isIsOperator && isInstantiableClass(concreteSubtype) && hasCustomEqualityMetaclass(concreteSubtype)) { | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
📍 packages/pyright-internal/src/analyzer/typeGuards.ts:2641 [verified] |
||
| return subtype; | ||
| } | ||
|
|
||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
For |
||
| if (isPositiveTest) { | ||
| if ( | ||
| isClassInstance(concreteSubtype) && | ||
|
|
@@ -2614,6 +2660,9 @@ function narrowTypeForClassComparison( | |
|
|
||
| if (isClass(concreteSubtype)) { | ||
| if (TypeBase.isInstance(concreteSubtype)) { | ||
| if (!isIsOperator) { | ||
| return subtype; | ||
| } | ||
| return ClassType.isBuiltIn(concreteSubtype, 'object') ? classType : undefined; | ||
| } | ||
|
|
||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,51 @@ | ||
| # This sample tests type narrowing when comparing class types | ||
| # with equality (== and !=) operators against class objects. | ||
|
|
||
| from typing import TypeVar, assert_type, final | ||
|
|
||
| class Base: pass | ||
| class Sub1(Base): pass | ||
|
|
||
| @final | ||
| class Sub2(Base): pass | ||
|
|
||
| T = TypeVar("T", bound=Base) | ||
|
|
||
| def test_eq_concrete(cls: type[Base]) -> type[Sub1]: | ||
| if cls == Sub1: | ||
| assert_type(cls, type[Sub1]) | ||
| return cls | ||
| raise ValueError() | ||
|
|
||
| def test_neq_concrete(cls: type[Sub1] | type[Sub2]): | ||
| if cls != Sub2: | ||
| assert_type(cls, type[Sub1]) | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Add a negative-boundary case for comparison with a non- |
||
|
|
||
| def test_neq_non_final(cls: type[Sub1] | type[Sub2]): | ||
| if cls != Sub1: | ||
| assert_type(cls, type[Sub1] | type[Sub2]) | ||
|
|
||
| def test_eq_typevar(cls: type[T]) -> type[Sub1]: | ||
| if cls == Sub1: | ||
| assert_type(cls, type[Sub1]) | ||
| return cls | ||
| raise ValueError() | ||
|
|
||
| class CustomMeta(type): | ||
| def __eq__(cls, other: object) -> bool: | ||
| return True | ||
|
|
||
| class Custom1(metaclass=CustomMeta): pass | ||
| class Custom2(metaclass=CustomMeta): pass | ||
|
|
||
| def test_eq_custom_meta(cls: type[Custom1] | type[Custom2]): | ||
| if cls == Custom1: | ||
| assert_type(cls, type[Custom1] | type[Custom2]) | ||
|
|
||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
This test returns at the RHS custom-metaclass guard, since both operands use |
||
| class EqualityDummy: | ||
| def __eq__(self, other: object) -> bool: | ||
| return True | ||
|
|
||
| def test_eq_instance_object(x: object): | ||
| if x == Sub1: | ||
| assert_type(x, object) | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
📍 packages/pyright-internal/src/tests/samples/typeGuard4.py:34 [verified] |
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -139,6 +139,11 @@ test('TypeGuard3', () => { | |
| TestUtils.validateResults(analysisResults, 0); | ||
| }); | ||
|
|
||
| test('TypeGuard4', () => { | ||
| const analysisResults = TestUtils.typeAnalyzeSampleFiles(['typeGuard4.py']); | ||
| TestUtils.validateResults(analysisResults, 0); | ||
| }); | ||
|
|
||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Add equivalent regression coverage under
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Please add equivalent regression coverage under |
||
| test('TypeIs1', () => { | ||
| const analysisResults = TestUtils.typeAnalyzeSampleFiles(['typeIs1.py']); | ||
| TestUtils.validateResults(analysisResults, 2); | ||
|
|
||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
📍 packages/pyright-internal/src/analyzer/typeGuards.ts:373
Verified behavior is operand-order dependent:
cls == Sub1narrows, butSub1 == clsdoes not. If equality narrowing remains supported, handle the reversed form or explicitly document and test why it must remain directional.[verified]