Skip to content

Commit

Permalink
Speed up LiteralType.__hash__ (#12540)
Browse files Browse the repository at this point in the history
It can be a bottleneck in some use cases.
  • Loading branch information
JukkaL authored Apr 7, 2022
1 parent ab1b488 commit 75e907d
Showing 1 changed file with 5 additions and 2 deletions.
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

0 comments on commit 75e907d

Please sign in to comment.