from collections.abc import Callable from functools import partial from typing import Any, cast import lazy_object_proxy Iter = list[Any] | dict[Any, Any] | Any IterPath = list[int | str] def traverse( obj: Iter, callback: Callable[[Iter, IterPath], Iter], path: IterPath | None = None, ) -> Iter: """ Traverse through nested dict or list. """ path = path or [] if isinstance(obj, dict): return { key: traverse(value, callback, path + [key]) for key, value in obj.items() } elif isinstance(obj, list): return [ traverse(elem, callback, path + [index]) for index, elem in enumerate(obj) ] return callback(obj, path) def lazy_proxy[T, **P]( factory: Callable[P, T], /, *args: P.args, **kwargs: P.kwargs ) -> T: """Create a lazy object proxy.""" return cast(T, lazy_object_proxy.Proxy(partial(factory, *args, **kwargs)))