lazy_loader.py 4.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. """Module to implement lazy loading in reflex.
  2. BSD 3-Clause License
  3. Copyright (c) 2022--2023, Scientific Python project All rights reserved.
  4. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
  5. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
  6. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
  7. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
  8. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  9. """
  10. from __future__ import annotations
  11. import copy
  12. import importlib
  13. import os
  14. import sys
  15. def attach(
  16. package_name: str,
  17. submodules: set[str] | None = None,
  18. submod_attrs: dict[str, list[str]] | None = None,
  19. ):
  20. """Replaces a package's __getattr__, __dir__, and __all__ attributes using lazy.attach.
  21. The lazy loader __getattr__ doesn't support tuples as list values. We needed to add
  22. this functionality (tuples) in Reflex to support 'import as _' statements. This function
  23. reformats the submod_attrs dictionary to flatten the module list before passing it to
  24. lazy_loader.
  25. Args:
  26. package_name: name of the package.
  27. submodules : List of submodules to attach.
  28. submod_attrs : Dictionary of submodule -> list of attributes / functions.
  29. These attributes are imported as they are used.
  30. Returns:
  31. __getattr__, __dir__, __all__
  32. """
  33. submod_attrs = copy.deepcopy(submod_attrs)
  34. if submod_attrs:
  35. for k, v in submod_attrs.items():
  36. # when flattening the list, only keep the alias in the tuple(mod[1])
  37. submod_attrs[k] = [
  38. mod if not isinstance(mod, tuple) else mod[1] for mod in v
  39. ]
  40. if submod_attrs is None:
  41. submod_attrs = {}
  42. submodules = set(submodules) if submodules is not None else set()
  43. attr_to_modules = {
  44. attr: mod for mod, attrs in submod_attrs.items() for attr in attrs
  45. }
  46. __all__ = sorted(submodules | attr_to_modules.keys())
  47. def __getattr__(name: str): # noqa: N807
  48. if name in submodules:
  49. return importlib.import_module(f"{package_name}.{name}")
  50. elif name in attr_to_modules:
  51. submod_path = f"{package_name}.{attr_to_modules[name]}"
  52. submod = importlib.import_module(submod_path)
  53. attr = getattr(submod, name)
  54. # If the attribute lives in a file (module) with the same
  55. # name as the attribute, ensure that the attribute and *not*
  56. # the module is accessible on the package.
  57. if name == attr_to_modules[name]:
  58. pkg = sys.modules[package_name]
  59. pkg.__dict__[name] = attr
  60. return attr
  61. else:
  62. raise AttributeError(f"No {package_name} attribute {name}")
  63. def __dir__(): # noqa: N807
  64. return __all__
  65. if os.environ.get("EAGER_IMPORT", ""):
  66. for attr in set(attr_to_modules.keys()) | submodules:
  67. __getattr__(attr)
  68. return __getattr__, __dir__, list(__all__)