lazy_forward.py 1.1 KB

1234567891011121314151617181920212223242526272829
  1. """Lazy forwarding helpers shared by the AIAgent façade and its mixins.
  2. Targets are resolved on every call, so ``patch("<module>.<name>")`` in tests still
  3. intercepts and the heavy agent modules stay off the ``run_agent`` import path.
  4. """
  5. import importlib
  6. def lazy_attr(module: str, name: str):
  7. """Resolve ``module.name`` at call time."""
  8. return getattr(importlib.import_module(module), name)
  9. def forward(module: str, name: str, *, static: bool = False):
  10. """Build an AIAgent method that lazily forwards to ``module.name``
  11. (``target(self, *args, **kwargs)``; ``static=True`` drops ``self``)."""
  12. if static:
  13. def forwarder(*args, **kwargs):
  14. return lazy_attr(module, name)(*args, **kwargs)
  15. else:
  16. def forwarder(self, *args, **kwargs):
  17. return lazy_attr(module, name)(self, *args, **kwargs)
  18. forwarder.__name__ = forwarder.__qualname__ = name
  19. forwarder.__doc__ = f"Forwarder — see ``{module}.{name}``."
  20. return staticmethod(forwarder) if static else forwarder
  21. def forward_static(module: str, name: str):
  22. return forward(module, name, static=True)