Skip to content

Commit

Permalink
Speed up Instance.__hash__
Browse files Browse the repository at this point in the history
This shows up as a bottleneck in some use cases, based on
profiling.

This should help with union simplification (#12526).
  • Loading branch information
JukkaL committed Apr 7, 2022
1 parent e7e1db6 commit 13494d7
Showing 1 changed file with 7 additions and 2 deletions.
9 changes: 7 additions & 2 deletions mypy/types.py
Original file line number Diff line number Diff line change
Expand Up @@ -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, *,
Expand Down Expand Up @@ -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):
Expand Down

0 comments on commit 13494d7

Please sign in to comment.