extension.py 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. import sys
  2. import re
  3. import functools
  4. import distutils.core
  5. import distutils.errors
  6. import distutils.extension
  7. from setuptools.extern.six.moves import map
  8. from .dist import _get_unpatched
  9. from . import msvc
  10. _Extension = _get_unpatched(distutils.core.Extension)
  11. msvc.patch_for_specialized_compiler()
  12. def _have_cython():
  13. """
  14. Return True if Cython can be imported.
  15. """
  16. cython_impl = 'Cython.Distutils.build_ext',
  17. try:
  18. # from (cython_impl) import build_ext
  19. __import__(cython_impl, fromlist=['build_ext']).build_ext
  20. return True
  21. except Exception:
  22. pass
  23. return False
  24. # for compatibility
  25. have_pyrex = _have_cython
  26. class Extension(_Extension):
  27. """Extension that uses '.c' files in place of '.pyx' files"""
  28. def _convert_pyx_sources_to_lang(self):
  29. """
  30. Replace sources with .pyx extensions to sources with the target
  31. language extension. This mechanism allows language authors to supply
  32. pre-converted sources but to prefer the .pyx sources.
  33. """
  34. if _have_cython():
  35. # the build has Cython, so allow it to compile the .pyx files
  36. return
  37. lang = self.language or ''
  38. target_ext = '.cpp' if lang.lower() == 'c++' else '.c'
  39. sub = functools.partial(re.sub, '.pyx$', target_ext)
  40. self.sources = list(map(sub, self.sources))
  41. class Library(Extension):
  42. """Just like a regular Extension, but built as a library instead"""
  43. distutils.core.Extension = Extension
  44. distutils.extension.Extension = Extension
  45. if 'distutils.command.build_ext' in sys.modules:
  46. sys.modules['distutils.command.build_ext'].Extension = Extension