8000 Speed up LiteralType.__hash__ · python/mypy@73e3ef4 · GitHub
[go: up one dir, main page]

Skip to content

Commit 73e3ef4

Browse files
committed
Speed up LiteralType.__hash__
It can be a bottleneck in some use cases. Work on #12526.
1 parent ab1b488 commit 73e3ef4

File tree

1 file changed

+5
-2
lines changed

1 file changed

+5
-2
lines changed

mypy/types.py

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2130,13 +2130,14 @@ class LiteralType(ProperType):
21302130
As another example, `Literal[Color.RED]` (where Color is an enum) is
21312131
represented as `LiteralType(value="RED", fallback=instance_of_color)'.
21322132
"""
2133-
__slots__ = ('value', 'fallback')
2133+
__slots__ = ('value', 'fallback', '_hash')
21342134

21352135
def __init__(self, value: LiteralValue, fallback: Instance,
21362136
line: int = -1, column: int = -1) -> None:
21372137
self.value = value
21382138
super().__init__(line, column)
21392139
self.fallback = fallback
2140+
self._hash = -1 # Cached hash value
21402141

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

21502151
def __hash__(self) -> int:
2151-
return hash((self.value, self.fallback))
2152+
if self._hash == -1:
2153+
self._hash = hash((self.value, self.fallback))
2154+
return self._hash
21522155

21532156
def __eq__(self, other: object) -> bool:
21542157
if isinstance(other, LiteralType):

0 commit comments

Comments
 (0)
0