[LazyLibrary] report full cycle when one is detected

This commit is contained in:
jan 2026-03-08 21:18:54 -07:00
commit 7eec2b7acf

View file

@ -1267,12 +1267,12 @@ class LazyLibrary(ILibrary):
"""
mapping: dict[str, Callable[[], 'Pattern']]
cache: dict[str, 'Pattern']
_lookups_in_progress: set[str]
_lookups_in_progress: list[str]
def __init__(self) -> None:
self.mapping = {}
self.cache = {}
self._lookups_in_progress = set()
self._lookups_in_progress = []
def __setitem__(
self,
@ -1303,16 +1303,20 @@ class LazyLibrary(ILibrary):
return self.cache[key]
if key in self._lookups_in_progress:
chain = ' -> '.join(self._lookups_in_progress + [key])
raise LibraryError(
f'Detected multiple simultaneous lookups of "{key}".\n'
f'Detected circular reference or recursive lookup of "{key}".\n'
f'Lookup chain: {chain}\n'
'This may be caused by an invalid (cyclical) reference, or buggy code.\n'
'If you are lazy-loading a file, try a non-lazy load and check for reference cycles.' # TODO give advice on finding cycles
'If you are lazy-loading a file, try a non-lazy load and check for reference cycles.'
)
self._lookups_in_progress.add(key)
self._lookups_in_progress.append(key)
try:
func = self.mapping[key]
pat = func()
self._lookups_in_progress.remove(key)
finally:
self._lookups_in_progress.pop()
self.cache[key] = pat
return pat