Skip to content

Fix false positive reportUnnecessaryComparison for bytes-like types - #11547

Open
pctablet505 wants to merge 1 commit into
microsoft:mainfrom
pctablet505:fix-bytes-bytearray-unnecessary-comparison
Open

Fix false positive reportUnnecessaryComparison for bytes-like types#11547
pctablet505 wants to merge 1 commit into
microsoft:mainfrom
pctablet505:fix-bytes-bytearray-unnecessary-comparison

Conversation

@pctablet505

Copy link
Copy Markdown

Fixes #11433

reportUnnecessaryComparison treats two disjoint built-in class instances as never comparable with ==/!=. That's a reasonable default, but it doesn't hold for bytes, bytearray and memoryview: they're unrelated for assignability purposes, yet their __eq__ implementations do support cross-type content comparisons (bytearray(4) == bytes(4) is True at runtime).

This adds a narrow carve-out in isTypeComparable for this specific group of types, reusing the existing typePromotions table that already models the relationship elsewhere (it's the same list consulted for the bytes/bytearray/memoryview assignability promotion). Comparability isn't gated behind disableBytesTypePromotions, since that setting is about assignment compatibility, not about whether __eq__ can return True.

Added test cases to comparison1.py covering bytearray/bytes, a bytearray-vs-literal-bytes comparison, and all pairings of bytes/bytearray/memoryview, alongside a couple of genuinely-disjoint builtin cases (int/str, list/dict) to confirm the general diagnostic still fires where it should.

The reportUnnecessaryComparison check assumed that any two disjoint
built-in class instances could never compare equal, which is true for
most types but not for "bytes", "bytearray" and "memoryview". These
types are otherwise unrelated for assignability purposes, but their
"__eq__" implementations do support cross-type content comparisons,
so "bytearray(4) == bytes(4)" is valid and can be True.

Fixes microsoft#11433
@pctablet505

Copy link
Copy Markdown
Author

@microsoft-github-policy-service agree

@pctablet505
pctablet505 marked this pull request as ready for review July 17, 2026 09:59
@rchiodo

rchiodo commented Jul 27, 2026

Copy link
Copy Markdown
Collaborator

🔒 Automated review in progress — @rchiodo is auto-reviewing this PR.

@rchiodo rchiodo left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Approved via Review Center.

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.

False positive: Condition will always evaluate to False since the types "bytearray" and "bytes" have no overlap

2 participants