lazy_loader.py 1.3 KB

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