test_lazyloading.py 1.1 KB

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