_multiarray_umath.py 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. from numpy._core import _multiarray_umath
  2. from numpy import ufunc
  3. for item in _multiarray_umath.__dir__():
  4. # ufuncs appear in pickles with a path in numpy.core._multiarray_umath
  5. # and so must import from this namespace without warning or error
  6. attr = getattr(_multiarray_umath, item)
  7. if isinstance(attr, ufunc):
  8. globals()[item] = attr
  9. def __getattr__(attr_name):
  10. from numpy._core import _multiarray_umath
  11. from ._utils import _raise_warning
  12. if attr_name in {"_ARRAY_API", "_UFUNC_API"}:
  13. from numpy.version import short_version
  14. import textwrap
  15. import traceback
  16. import sys
  17. msg = textwrap.dedent(f"""
  18. A module that was compiled using NumPy 1.x cannot be run in
  19. NumPy {short_version} as it may crash. To support both 1.x and 2.x
  20. versions of NumPy, modules must be compiled with NumPy 2.0.
  21. Some module may need to rebuild instead e.g. with 'pybind11>=2.12'.
  22. If you are a user of the module, the easiest solution will be to
  23. downgrade to 'numpy<2' or try to upgrade the affected module.
  24. We expect that some modules will need time to support NumPy 2.
  25. """)
  26. tb_msg = "Traceback (most recent call last):"
  27. for line in traceback.format_stack()[:-1]:
  28. if "frozen importlib" in line:
  29. continue
  30. tb_msg += line
  31. # Also print the message (with traceback). This is because old versions
  32. # of NumPy unfortunately set up the import to replace (and hide) the
  33. # error. The traceback shouldn't be needed, but e.g. pytest plugins
  34. # seem to swallow it and we should be failing anyway...
  35. sys.stderr.write(msg + tb_msg)
  36. raise ImportError(msg)
  37. ret = getattr(_multiarray_umath, attr_name, None)
  38. if ret is None:
  39. raise AttributeError(
  40. "module 'numpy.core._multiarray_umath' has no attribute "
  41. f"{attr_name}")
  42. _raise_warning(attr_name, "_multiarray_umath")
  43. return ret
  44. del _multiarray_umath, ufunc