Skip to content
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

Speed up LiteralType.__hash__ #12540

Merged
merged 1 commit into from
Apr 7, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 5 additions & 2 deletions mypy/types.py
Original file line number Diff line number Diff line change
Expand Up @@ -2130,13 +2130,14 @@ class LiteralType(ProperType):
As another example, `Literal[Color.RED]` (where Color is an enum) is
represented as `LiteralType(value="RED", fallback=instance_of_color)'.
"""
__slots__ = ('value', 'fallback')
__slots__ = ('value', 'fallback', '_hash')

def __init__(self, value: LiteralValue, fallback: Instance,
line: int = -1, column: int = -1) -> None:
self.value = value
super().__init__(line, column)
self.fallback = fallback
self._hash = -1 # Cached hash value

def can_be_false_default(self) -> bool:
return not self.value
Expand All @@ -2148,7 +2149,9 @@ def accept(self, visitor: 'TypeVisitor[T]') -> T:
return visitor.visit_literal_type(self)

def __hash__(self) -> int:
return hash((self.value, self.fallback))
if self._hash == -1:
self._hash = hash((self.value, self.fallback))
return self._hash

def __eq__(self, other: object) -> bool:
if isinstance(other, LiteralType):
Expand Down