Skip to content

Commit 445e823

Browse files
Optimization: cache the hashes of nodes (#150)
1 parent 28772a2 commit 445e823

File tree

1 file changed

+8
-2
lines changed

1 file changed

+8
-2
lines changed

src/graphql/language/ast.py

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -226,7 +226,7 @@ class Node:
226226
"""AST nodes"""
227227

228228
# allow custom attributes and weak references (not used internally)
229-
__slots__ = "__dict__", "__weakref__", "loc"
229+
__slots__ = "__dict__", "__weakref__", "loc", "_hash"
230230

231231
loc: Optional[Location]
232232

@@ -255,7 +255,13 @@ def __eq__(self, other: Any) -> bool:
255255
)
256256

257257
def __hash__(self) -> int:
258-
return hash(tuple(getattr(self, key) for key in self.keys))
258+
if getattr(self, "_hash", None) is None:
259+
self._hash = hash(tuple(getattr(self, key) for key in self.keys))
260+
return self._hash
261+
262+
def __setattr__(self, key, value):
263+
object.__setattr__(self, "_hash", None)
264+
super().__setattr__(key, value)
259265

260266
def __copy__(self) -> "Node":
261267
"""Create a shallow copy of the node."""

0 commit comments

Comments
 (0)