From fc412d71904bc28a592246630943159369ab1a55 Mon Sep 17 00:00:00 2001 From: Alec Rosenbaum Date: Fri, 10 Dec 2021 10:26:42 -0500 Subject: [PATCH 1/2] cache node hashing --- src/graphql/language/ast.py | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/graphql/language/ast.py b/src/graphql/language/ast.py index a4a6fb3a..a649a9c5 100644 --- a/src/graphql/language/ast.py +++ b/src/graphql/language/ast.py @@ -226,7 +226,7 @@ class Node: """AST nodes""" # allow custom attributes and weak references (not used internally) - __slots__ = "__dict__", "__weakref__", "loc" + __slots__ = "__dict__", "__weakref__", "loc", "_hash" loc: Optional[Location] @@ -255,7 +255,9 @@ def __eq__(self, other: Any) -> bool: ) def __hash__(self) -> int: - return hash(tuple(getattr(self, key) for key in self.keys)) + if getattr(self, "_hash", None) is None: + self._hash = hash(tuple(getattr(self, key) for key in self.keys)) + return self._hash def __copy__(self) -> "Node": """Create a shallow copy of the node.""" From 8363365a84df546b3bd63c3c3ed532ea4d536d13 Mon Sep 17 00:00:00 2001 From: Alec Rosenbaum Date: Fri, 10 Dec 2021 11:11:11 -0500 Subject: [PATCH 2/2] add __setattr__ override to invalidate _hash --- src/graphql/language/ast.py | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/graphql/language/ast.py b/src/graphql/language/ast.py index a649a9c5..d9a2e80a 100644 --- a/src/graphql/language/ast.py +++ b/src/graphql/language/ast.py @@ -259,6 +259,10 @@ def __hash__(self) -> int: self._hash = hash(tuple(getattr(self, key) for key in self.keys)) return self._hash + def __setattr__(self, key, value): + object.__setattr__(self, "_hash", None) + super().__setattr__(key, value) + def __copy__(self) -> "Node": """Create a shallow copy of the node.""" return self.__class__(**{key: getattr(self, key) for key in self.keys})