From 75e907d95f99da5b21e83caa94b5734459ce8916 Mon Sep 17 00:00:00 2001 From: Jukka Lehtosalo Date: Thu, 7 Apr 2022 17:27:53 +0100 Subject: [PATCH] Speed up LiteralType.__hash__ (#12540) It can be a bottleneck in some use cases. --- mypy/types.py | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/mypy/types.py b/mypy/types.py index 487dd1387bad..07f7cc845773 100644 --- a/mypy/types.py +++ b/mypy/types.py @@ -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 @@ -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):