Extended support for reportUnnecessaryComparison check to handle dataclass types that use a synthesized __eq__ method. This addresses https://github.com/microsoft/pyright/issues/3034.

This commit is contained in:
Eric Traut 2023-03-20 12:41:02 -06:00
parent 54dbe9a8bd
commit d860256d58
3 changed files with 26 additions and 8 deletions

View File

@ -2057,13 +2057,19 @@ export class Checker extends ParseTreeWalker {
}
// Does the class have an operator overload for eq?
if (
lookUpClassMember(
ClassType.cloneAsInstantiable(leftType),
'__eq__',
ClassMemberLookupFlags.SkipObjectBaseClass
)
) {
const eqMethod = lookUpClassMember(
ClassType.cloneAsInstantiable(leftType),
'__eq__',
ClassMemberLookupFlags.SkipObjectBaseClass
);
if (eqMethod) {
// If this is a synthesized method for a dataclass, we can assume
// that other dataclass types will not be comparable.
if (ClassType.isDataClass(leftType) && eqMethod.symbol.getSynthesizedType()) {
return false;
}
return true;
}

View File

@ -3,6 +3,7 @@
from typing import Any
from dataclasses import dataclass
def cond() -> bool:
@ -54,3 +55,14 @@ if c is not None:
def func2(d: str | Any):
if d is None:
pass
@dataclass
class DC1:
bar: str
def func3(x: DC1):
# This should generate an error if reportUnnecessaryComparison is enabled.
if x == 42:
...

View File

@ -1230,7 +1230,7 @@ test('Comparison2', () => {
configOptions.diagnosticRuleSet.reportUnnecessaryComparison = 'error';
const analysisResults2 = TestUtils.typeAnalyzeSampleFiles(['comparison2.py'], configOptions);
TestUtils.validateResults(analysisResults2, 9);
TestUtils.validateResults(analysisResults2, 10);
});
test('EmptyContainers1', () => {