From 13494d7e20fc46c050177743b807cb80b9822e4e Mon Sep 17 00:00:00 2001 From: Jukka Lehtosalo Date: Thu, 7 Apr 2022 12:52:00 +0100 Subject: [PATCH] Speed up Instance.__hash__ This shows up as a bottleneck in some use cases, based on profiling. This should help with union simplification (#12526). --- mypy/types.py | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/mypy/types.py b/mypy/types.py index 06cf3f9e9dff..487dd1387bad 100644 --- a/mypy/types.py +++ b/mypy/types.py @@ -1049,7 +1049,7 @@ def try_getting_instance_fallback(typ: ProperType) -> Optional[Instance]: """ - __slots__ = ('type', 'args', 'invalid', 'type_ref', 'last_known_value') + __slots__ = ('type', 'args', 'invalid', 'type_ref', 'last_known_value', '_hash') def __init__(self, typ: mypy.nodes.TypeInfo, args: Sequence[Type], line: int = -1, column: int = -1, *, @@ -1107,11 +1107,16 @@ def __init__(self, typ: mypy.nodes.TypeInfo, args: Sequence[Type], # Literal context. self.last_known_value = last_known_value + # Cached hash value + self._hash = -1 + def accept(self, visitor: 'TypeVisitor[T]') -> T: return visitor.visit_instance(self) def __hash__(self) -> int: - return hash((self.type, tuple(self.args), self.last_known_value)) + if self._hash == -1: + self._hash = hash((self.type, self.args, self.last_known_value)) + return self._hash def __eq__(self, other: object) -> bool: if not isinstance(other, Instance):