_shimmed_dist_utils.py 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. """
  2. Temporary shim module to indirect the bits of distutils we need from setuptools/distutils while providing useful
  3. error messages beyond `No module named 'distutils' on Python >= 3.12, or when setuptools' vendored distutils is broken.
  4. This is a compromise to avoid a hard-dep on setuptools for Python >= 3.12, since many users don't need runtime compilation support from CFFI.
  5. """
  6. import sys
  7. try:
  8. # import setuptools first; this is the most robust way to ensure its embedded distutils is available
  9. # (the .pth shim should usually work, but this is even more robust)
  10. import setuptools
  11. except Exception as ex:
  12. if sys.version_info >= (3, 12):
  13. # Python 3.12 has no built-in distutils to fall back on, so any import problem is fatal
  14. raise Exception("This CFFI feature requires setuptools on Python >= 3.12. The setuptools module is missing or non-functional.") from ex
  15. # silently ignore on older Pythons (support fallback to stdlib distutils where available)
  16. else:
  17. del setuptools
  18. try:
  19. # bring in just the bits of distutils we need, whether they really came from setuptools or stdlib-embedded distutils
  20. from distutils import log, sysconfig
  21. from distutils.ccompiler import CCompiler
  22. from distutils.command.build_ext import build_ext
  23. from distutils.core import Distribution, Extension
  24. from distutils.dir_util import mkpath
  25. from distutils.errors import DistutilsSetupError, CompileError, LinkError
  26. from distutils.log import set_threshold, set_verbosity
  27. if sys.platform == 'win32':
  28. try:
  29. # FUTURE: msvc9compiler module was removed in setuptools 74; consider removing, as it's only used by an ancient patch in `recompiler`
  30. from distutils.msvc9compiler import MSVCCompiler
  31. except ImportError:
  32. MSVCCompiler = None
  33. except Exception as ex:
  34. if sys.version_info >= (3, 12):
  35. raise Exception("This CFFI feature requires setuptools on Python >= 3.12. Please install the setuptools package.") from ex
  36. # anything older, just let the underlying distutils import error fly
  37. raise Exception("This CFFI feature requires distutils. Please install the distutils or setuptools package.") from ex
  38. del sys