Skip to content

Optimise LiteralType.__eq__ and __hash__#20423

Merged
ilevkivskyi merged 3 commits intopython:masterfrom
hauntsaninja:mypylit
Jan 26, 2026
Merged

Optimise LiteralType.__eq__ and __hash__#20423
ilevkivskyi merged 3 commits intopython:masterfrom
hauntsaninja:mypylit

Conversation

@hauntsaninja
Copy link
Copy Markdown
Collaborator

@hauntsaninja hauntsaninja commented Dec 16, 2025

If I'm doing it right, this should be 1-2% on a profile I'm looking at

If I'm doing it right, this should be 2% on a profile I'm looking at
@github-actions

This comment has been minimized.

if self._hash == -1:
self._hash = hash((self.value, self.fallback))
return self._hash
return hash(self.value)
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Is this part actually safe? This will make Literal["foo"] and Literal[b"foo"] have same hash (I don't remember why, but we always store the literal bytes value as a string).

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.

There's also Literal[0] vs Literal[False], both 0 and False hash to zero IIRC

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

It's fine for hashes to collide and doesn't affect correctness. You just don't want too many values to collide because then some of your constant time operations become linear.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Only correctness requirement is that values that compare equal have the same hash

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

OK, I see, could you please then add a comment explaining this pef optimization, otherwise it looks like a "typo". Otherwise this PR LG.

@hauntsaninja hauntsaninja marked this pull request as ready for review January 26, 2026 20:00
@github-actions
Copy link
Copy Markdown
Contributor

According to mypy_primer, this change doesn't affect type check results on a corpus of open source code. ✅

@ilevkivskyi ilevkivskyi merged commit a940c8f into python:master Jan 26, 2026
23 checks passed
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.

3 participants