lazy_loader.py 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. """Module to implement lazy loading in reflex."""
  2. from __future__ import annotations
  3. import copy
  4. import lazy_loader as lazy
  5. def attach(
  6. package_name: str,
  7. submodules: set | None = None,
  8. submod_attrs: dict | None = None,
  9. ):
  10. """Replaces a package's __getattr__, __dir__, and __all__ attributes using lazy.attach.
  11. The lazy loader __getattr__ doesn't support tuples as list values. We needed to add
  12. this functionality (tuples) in Reflex to support 'import as _' statements. This function
  13. reformats the submod_attrs dictionary to flatten the module list before passing it to
  14. lazy_loader.
  15. Args:
  16. package_name: name of the package.
  17. submodules : List of submodules to attach.
  18. submod_attrs : Dictionary of submodule -> list of attributes / functions.
  19. These attributes are imported as they are used.
  20. Returns:
  21. __getattr__, __dir__, __all__
  22. """
  23. _submod_attrs = copy.deepcopy(submod_attrs)
  24. if _submod_attrs:
  25. for k, v in _submod_attrs.items():
  26. # when flattening the list, only keep the alias in the tuple(mod[1])
  27. _submod_attrs[k] = [
  28. mod if not isinstance(mod, tuple) else mod[1] for mod in v
  29. ]
  30. return lazy.attach(
  31. package_name=package_name, submodules=submodules, submod_attrs=_submod_attrs
  32. )