Skip to content

Commit 0c63af8

Browse files
committed
Cache create_intersection results.
1 parent 7ecdd9e commit 0c63af8

File tree

1 file changed

+23
-2
lines changed

1 file changed

+23
-2
lines changed

gel/_internal/_qbmodel/_abstract/_methods.py

Lines changed: 23 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@
1414
TypeVar,
1515
)
1616
from typing_extensions import Self
17-
17+
import weakref
1818

1919
from gel._internal import _qb
2020
from gel._internal._schemapath import (
@@ -300,13 +300,30 @@ def combine_dicts(
300300
return result
301301

302302

303-
# TODO: We should cache the results of this
303+
_type_intersection_cache: weakref.WeakKeyDictionary[
304+
type[AbstractGelModel],
305+
weakref.WeakKeyDictionary[
306+
type[AbstractGelModel],
307+
type[
308+
BaseGelModelIntersection[
309+
type[AbstractGelModel], type[AbstractGelModel]
310+
]
311+
],
312+
],
313+
] = weakref.WeakKeyDictionary()
314+
315+
304316
def create_intersection(
305317
lhs: _T_Lhs,
306318
rhs: _T_Rhs,
307319
) -> type[BaseGelModelIntersection[_T_Lhs, _T_Rhs]]:
308320
"""Create a runtime intersection type which acts like a GelModel."""
309321

322+
if (lhs_entry := _type_intersection_cache.get(lhs)) and (
323+
rhs_entry := lhs_entry.get(rhs)
324+
):
325+
return rhs_entry # type: ignore[return-value]
326+
310327
# Combine pointer reflections from args
311328
ptr_reflections: dict[str, _qb.GelPointerReflection] = combine_dicts(
312329
lhs.__gel_reflection__.pointers,
@@ -403,4 +420,8 @@ def process_path_alias(
403420
for p_name, path_alias in path_aliases.items():
404421
setattr(result, p_name, path_alias)
405422

423+
if lhs not in _type_intersection_cache:
424+
_type_intersection_cache[lhs] = weakref.WeakKeyDictionary()
425+
_type_intersection_cache[lhs][rhs] = result
426+
406427
return result

0 commit comments

Comments
 (0)