test_lazyloading.py 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. import sys
  2. from importlib.util import LazyLoader, find_spec, module_from_spec
  3. import pytest
  4. # Warning raised by _reload_guard() in numpy/__init__.py
  5. @pytest.mark.filterwarnings("ignore:The NumPy module was reloaded")
  6. def test_lazy_load():
  7. # gh-22045. lazyload doesn't import submodule names into the namespace
  8. # muck with sys.modules to test the importing system
  9. old_numpy = sys.modules.pop("numpy")
  10. numpy_modules = {}
  11. for mod_name, mod in list(sys.modules.items()):
  12. if mod_name[:6] == "numpy.":
  13. numpy_modules[mod_name] = mod
  14. sys.modules.pop(mod_name)
  15. try:
  16. # create lazy load of numpy as np
  17. spec = find_spec("numpy")
  18. module = module_from_spec(spec)
  19. sys.modules["numpy"] = module
  20. loader = LazyLoader(spec.loader)
  21. loader.exec_module(module)
  22. np = module
  23. # test a subpackage import
  24. from numpy.lib import recfunctions # noqa: F401
  25. # test triggering the import of the package
  26. np.ndarray
  27. finally:
  28. if old_numpy:
  29. sys.modules["numpy"] = old_numpy
  30. sys.modules.update(numpy_modules)