Skip to content

Better narrowing for enums and other types with known equality#21281

Open
hauntsaninja wants to merge 1 commit intopython:masterfrom
hauntsaninja:enumident2
Open

Better narrowing for enums and other types with known equality#21281
hauntsaninja wants to merge 1 commit intopython:masterfrom
hauntsaninja:enumident2

Conversation

@hauntsaninja
Copy link
Copy Markdown
Collaborator

@hauntsaninja hauntsaninja commented Apr 21, 2026

Fixes #21187, fully fixes this comment #9003 (comment) (previously improved on in 1.20 narrowing changes)

This diff adds general functionality that replaces a few different pieces of ad hoc logic:

  • The conservative enum handling is now generalised
  • We can get rid of the special cased logic for None when narrowing contains, it is fully subsumed by more general logic
  • We no longer rely on promotion behaviour to narrow numeric types correctly
  • Similarly, we now narrow bytes consistently, regardless of --strict-bytes. We also no longer have to mark memoryview and bytearray as having custom equality implementations. That is, it is a long term fix for Optional bytes type not narrowed after asserting equality #20701

Co-authored-by Codex

@github-actions
Copy link
Copy Markdown
Contributor

Diff from mypy_primer, showing the effect of this PR on open source code:

rich (https://github.com/Textualize/rich)
+ rich/console.py:1542: error: Redundant cast to "Literal['left', 'center', 'right']"  [redundant-cast]

cryptography (https://github.com/pyca/cryptography)
+ src/cryptography/hazmat/primitives/serialization/ssh.py:1120: error: Argument 16 to "SSHCertificate" has incompatible type "bytes | Any | memoryview[int]"; expected "bytes"  [arg-type]

@hauntsaninja hauntsaninja marked this pull request as ready for review April 21, 2026 07:59
@hauntsaninja hauntsaninja changed the title Better narrowing for enums and other known types with equality Better narrowing for enums and other types with known equality Apr 21, 2026
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.

[1.20 regression] Type narrowing is order sensitive in match-case statement with narrowed enum type

1 participant