distutils_patch.py 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. """
  2. Ensure that the local copy of distutils is preferred over stdlib.
  3. See https://github.com/pypa/setuptools/issues/417#issuecomment-392298401
  4. for more motivation.
  5. """
  6. import sys
  7. import re
  8. import os
  9. import importlib
  10. import warnings
  11. is_pypy = '__pypy__' in sys.builtin_module_names
  12. def warn_distutils_present():
  13. if 'distutils' not in sys.modules:
  14. return
  15. if is_pypy and sys.version_info < (3, 7):
  16. # PyPy for 3.6 unconditionally imports distutils, so bypass the warning
  17. # https://foss.heptapod.net/pypy/pypy/-/blob/be829135bc0d758997b3566062999ee8b23872b4/lib-python/3/site.py#L250
  18. return
  19. warnings.warn(
  20. "Distutils was imported before Setuptools. This usage is discouraged "
  21. "and may exhibit undesirable behaviors or errors. Please use "
  22. "Setuptools' objects directly or at least import Setuptools first.")
  23. def clear_distutils():
  24. if 'distutils' not in sys.modules:
  25. return
  26. warnings.warn("Setuptools is replacing distutils.")
  27. mods = [name for name in sys.modules if re.match(r'distutils\b', name)]
  28. for name in mods:
  29. del sys.modules[name]
  30. def enabled():
  31. """
  32. Allow selection of distutils by environment variable.
  33. """
  34. which = os.environ.get('SETUPTOOLS_USE_DISTUTILS', 'stdlib')
  35. return which == 'local'
  36. def ensure_local_distutils():
  37. clear_distutils()
  38. distutils = importlib.import_module('setuptools._distutils')
  39. distutils.__name__ = 'distutils'
  40. sys.modules['distutils'] = distutils
  41. # sanity check that submodules load as expected
  42. core = importlib.import_module('distutils.core')
  43. assert '_distutils' in core.__file__, core.__file__
  44. warn_distutils_present()
  45. if enabled():
  46. ensure_local_distutils()