extension.py 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179
  1. from __future__ import annotations
  2. import functools
  3. import re
  4. from collections.abc import Iterable
  5. from typing import TYPE_CHECKING
  6. from setuptools._path import StrPath
  7. from .monkey import get_unpatched
  8. import distutils.core
  9. import distutils.errors
  10. import distutils.extension
  11. def _have_cython() -> bool:
  12. """
  13. Return True if Cython can be imported.
  14. """
  15. cython_impl = 'Cython.Distutils.build_ext'
  16. try:
  17. # from (cython_impl) import build_ext
  18. __import__(cython_impl, fromlist=['build_ext']).build_ext
  19. except Exception:
  20. return False
  21. return True
  22. # for compatibility
  23. have_pyrex = _have_cython
  24. if TYPE_CHECKING:
  25. # Work around a mypy issue where type[T] can't be used as a base: https://github.com/python/mypy/issues/10962
  26. from distutils.core import Extension as _Extension
  27. else:
  28. _Extension = get_unpatched(distutils.core.Extension)
  29. class Extension(_Extension):
  30. """
  31. Describes a single extension module.
  32. This means that all source files will be compiled into a single binary file
  33. ``<module path>.<suffix>`` (with ``<module path>`` derived from ``name`` and
  34. ``<suffix>`` defined by one of the values in
  35. ``importlib.machinery.EXTENSION_SUFFIXES``).
  36. In the case ``.pyx`` files are passed as ``sources and`` ``Cython`` is **not**
  37. installed in the build environment, ``setuptools`` may also try to look for the
  38. equivalent ``.cpp`` or ``.c`` files.
  39. :arg str name:
  40. the full name of the extension, including any packages -- ie.
  41. *not* a filename or pathname, but Python dotted name
  42. :arg Iterable[str | os.PathLike[str]] sources:
  43. iterable of source filenames, (except strings, which could be misinterpreted
  44. as a single filename), relative to the distribution root
  45. (where the setup script lives), in Unix form (slash-separated)
  46. for portability. Source files may be C, C++, SWIG (.i),
  47. platform-specific resource files, or whatever else is recognized
  48. by the "build_ext" command as source for a Python extension.
  49. :keyword list[str] include_dirs:
  50. list of directories to search for C/C++ header files (in Unix
  51. form for portability)
  52. :keyword list[tuple[str, str|None]] define_macros:
  53. list of macros to define; each macro is defined using a 2-tuple:
  54. the first item corresponding to the name of the macro and the second
  55. item either a string with its value or None to
  56. define it without a particular value (equivalent of "#define
  57. FOO" in source or -DFOO on Unix C compiler command line)
  58. :keyword list[str] undef_macros:
  59. list of macros to undefine explicitly
  60. :keyword list[str] library_dirs:
  61. list of directories to search for C/C++ libraries at link time
  62. :keyword list[str] libraries:
  63. list of library names (not filenames or paths) to link against
  64. :keyword list[str] runtime_library_dirs:
  65. list of directories to search for C/C++ libraries at run time
  66. (for shared extensions, this is when the extension is loaded).
  67. Setting this will cause an exception during build on Windows
  68. platforms.
  69. :keyword list[str] extra_objects:
  70. list of extra files to link with (eg. object files not implied
  71. by 'sources', static library that must be explicitly specified,
  72. binary resource files, etc.)
  73. :keyword list[str] extra_compile_args:
  74. any extra platform- and compiler-specific information to use
  75. when compiling the source files in 'sources'. For platforms and
  76. compilers where "command line" makes sense, this is typically a
  77. list of command-line arguments, but for other platforms it could
  78. be anything.
  79. :keyword list[str] extra_link_args:
  80. any extra platform- and compiler-specific information to use
  81. when linking object files together to create the extension (or
  82. to create a new static Python interpreter). Similar
  83. interpretation as for 'extra_compile_args'.
  84. :keyword list[str] export_symbols:
  85. list of symbols to be exported from a shared extension. Not
  86. used on all platforms, and not generally necessary for Python
  87. extensions, which typically export exactly one symbol: "init" +
  88. extension_name.
  89. :keyword list[str] swig_opts:
  90. any extra options to pass to SWIG if a source file has the .i
  91. extension.
  92. :keyword list[str] depends:
  93. list of files that the extension depends on
  94. :keyword str language:
  95. extension language (i.e. "c", "c++", "objc"). Will be detected
  96. from the source extensions if not provided.
  97. :keyword bool optional:
  98. specifies that a build failure in the extension should not abort the
  99. build process, but simply not install the failing extension.
  100. :keyword bool py_limited_api:
  101. opt-in flag for the usage of :doc:`Python's limited API <python:c-api/stable>`.
  102. :raises setuptools.errors.PlatformError: if ``runtime_library_dirs`` is
  103. specified on Windows. (since v63)
  104. """
  105. # These 4 are set and used in setuptools/command/build_ext.py
  106. # The lack of a default value and risk of `AttributeError` is purposeful
  107. # to avoid people forgetting to call finalize_options if they modify the extension list.
  108. # See example/rationale in https://github.com/pypa/setuptools/issues/4529.
  109. _full_name: str #: Private API, internal use only.
  110. _links_to_dynamic: bool #: Private API, internal use only.
  111. _needs_stub: bool #: Private API, internal use only.
  112. _file_name: str #: Private API, internal use only.
  113. def __init__(
  114. self,
  115. name: str,
  116. sources: Iterable[StrPath],
  117. *args,
  118. py_limited_api: bool = False,
  119. **kw,
  120. ) -> None:
  121. # The *args is needed for compatibility as calls may use positional
  122. # arguments. py_limited_api may be set only via keyword.
  123. self.py_limited_api = py_limited_api
  124. super().__init__(
  125. name,
  126. sources, # type: ignore[arg-type] # Vendored version of setuptools supports PathLike
  127. *args,
  128. **kw,
  129. )
  130. def _convert_pyx_sources_to_lang(self):
  131. """
  132. Replace sources with .pyx extensions to sources with the target
  133. language extension. This mechanism allows language authors to supply
  134. pre-converted sources but to prefer the .pyx sources.
  135. """
  136. if _have_cython():
  137. # the build has Cython, so allow it to compile the .pyx files
  138. return
  139. lang = self.language or ''
  140. target_ext = '.cpp' if lang.lower() == 'c++' else '.c'
  141. sub = functools.partial(re.sub, '.pyx$', target_ext)
  142. self.sources = list(map(sub, self.sources))
  143. class Library(Extension):
  144. """Just like a regular Extension, but built as a library instead"""