1 # This file is dual licensed under the terms of the Apache License, Version
2 # 2.0, and the BSD License. See the LICENSE file in the root of this repository
3 # for complete details.
10 from importlib
.machinery
import EXTENSION_SUFFIXES
24 from . import _manylinux
, _musllinux
26 logger
= logging
.getLogger(__name__
)
28 PythonVersion
= Sequence
[int]
29 MacVersion
= Tuple
[int, int]
31 INTERPRETER_SHORT_NAMES
: Dict
[str, str] = {
32 "python": "py", # Generic.
40 _32_BIT_INTERPRETER
= sys
.maxsize
<= 2**32
45 A representation of the tag triple for a wheel.
47 Instances are considered immutable and thus are hashable. Equality checking
51 __slots__
= ["_interpreter", "_abi", "_platform", "_hash"]
53 def __init__(self
, interpreter
: str, abi
: str, platform
: str) -> None:
54 self
._interpreter
= interpreter
.lower()
55 self
._abi
= abi
.lower()
56 self
._platform
= platform
.lower()
57 # The __hash__ of every single element in a Set[Tag] will be evaluated each time
58 # that a set calls its `.disjoint()` method, which may be called hundreds of
59 # times when scanning a page of links for packages with tags matching that
60 # Set[Tag]. Pre-computing the value here produces significant speedups for
61 # downstream consumers.
62 self
._hash
= hash((self
._interpreter
, self
._abi
, self
._platform
))
65 def interpreter(self
) -> str:
66 return self
._interpreter
73 def platform(self
) -> str:
76 def __eq__(self
, other
: object) -> bool:
77 if not isinstance(other
, Tag
):
81 (self
._hash
== other
._hash
) # Short-circuit ASAP for perf reasons.
82 and (self
._platform
== other
._platform
)
83 and (self
._abi
== other
._abi
)
84 and (self
._interpreter
== other
._interpreter
)
87 def __hash__(self
) -> int:
90 def __str__(self
) -> str:
91 return f
"{self._interpreter}-{self._abi}-{self._platform}"
93 def __repr__(self
) -> str:
94 return f
"<{self} @ {id(self)}>"
97 def parse_tag(tag
: str) -> FrozenSet
[Tag
]:
99 Parses the provided tag (e.g. `py3-none-any`) into a frozenset of Tag instances.
101 Returning a set is required due to the possibility that the tag is a
105 interpreters
, abis
, platforms
= tag
.split("-")
106 for interpreter
in interpreters
.split("."):
107 for abi
in abis
.split("."):
108 for platform_
in platforms
.split("."):
109 tags
.add(Tag(interpreter
, abi
, platform_
))
110 return frozenset(tags
)
113 def _get_config_var(name
: str, warn
: bool = False) -> Union
[int, str, None]:
114 value
: Union
[int, str, None] = sysconfig
.get_config_var(name
)
115 if value
is None and warn
:
117 "Config variable '%s' is unset, Python ABI tag may be incorrect", name
122 def _normalize_string(string
: str) -> str:
123 return string
.replace(".", "_").replace("-", "_").replace(" ", "_")
126 def _abi3_applies(python_version
: PythonVersion
) -> bool:
128 Determine if the Python version supports abi3.
130 PEP 384 was first implemented in Python 3.2.
132 return len(python_version
) > 1 and tuple(python_version
) >= (3, 2)
135 def _cpython_abis(py_version
: PythonVersion
, warn
: bool = False) -> List
[str]:
136 py_version
= tuple(py_version
) # To allow for version comparison.
138 version
= _version_nodot(py_version
[:2])
139 debug
= pymalloc
= ucs4
= ""
140 with_debug
= _get_config_var("Py_DEBUG", warn
)
141 has_refcount
= hasattr(sys
, "gettotalrefcount")
142 # Windows doesn't set Py_DEBUG, so checking for support of debug-compiled
143 # extension modules is the best option.
144 # https://github.com/pypa/pip/issues/3383#issuecomment-173267692
145 has_ext
= "_d.pyd" in EXTENSION_SUFFIXES
146 if with_debug
or (with_debug
is None and (has_refcount
or has_ext
)):
148 if py_version
< (3, 8):
149 with_pymalloc
= _get_config_var("WITH_PYMALLOC", warn
)
150 if with_pymalloc
or with_pymalloc
is None:
152 if py_version
< (3, 3):
153 unicode_size
= _get_config_var("Py_UNICODE_SIZE", warn
)
154 if unicode_size
== 4 or (
155 unicode_size
is None and sys
.maxunicode
== 0x10FFFF
159 # Debug builds can also load "normal" extension modules.
160 # We can also assume no UCS-4 or pymalloc requirement.
161 abis
.append(f
"cp{version}")
164 "cp{version}{debug}{pymalloc}{ucs4}".format(
165 version
=version
, debug
=debug
, pymalloc
=pymalloc
, ucs4
=ucs4
172 python_version
: Optional
[PythonVersion
] = None,
173 abis
: Optional
[Iterable
[str]] = None,
174 platforms
: Optional
[Iterable
[str]] = None,
179 Yields the tags for a CPython interpreter.
182 - cp<python_version>-<abi>-<platform>
183 - cp<python_version>-abi3-<platform>
184 - cp<python_version>-none-<platform>
185 - cp<less than python_version>-abi3-<platform> # Older Python versions down to 3.2.
187 If python_version only specifies a major version then user-provided ABIs and
188 the 'none' ABItag will be used.
190 If 'abi3' or 'none' are specified in 'abis' then they will be yielded at
191 their normal position and not at the beginning.
193 if not python_version
:
194 python_version
= sys
.version_info
[:2]
196 interpreter
= f
"cp{_version_nodot(python_version[:2])}"
199 if len(python_version
) > 1:
200 abis
= _cpython_abis(python_version
, warn
)
204 # 'abi3' and 'none' are explicitly handled later.
205 for explicit_abi
in ("abi3", "none"):
207 abis
.remove(explicit_abi
)
211 platforms
= list(platforms
or platform_tags())
213 for platform_
in platforms
:
214 yield Tag(interpreter
, abi
, platform_
)
215 if _abi3_applies(python_version
):
216 yield from (Tag(interpreter
, "abi3", platform_
) for platform_
in platforms
)
217 yield from (Tag(interpreter
, "none", platform_
) for platform_
in platforms
)
219 if _abi3_applies(python_version
):
220 for minor_version
in range(python_version
[1] - 1, 1, -1):
221 for platform_
in platforms
:
222 interpreter
= "cp{version}".format(
223 version
=_version_nodot((python_version
[0], minor_version
))
225 yield Tag(interpreter
, "abi3", platform_
)
228 def _generic_abi() -> List
[str]:
230 Return the ABI tag based on EXT_SUFFIX.
232 # The following are examples of `EXT_SUFFIX`.
233 # We want to keep the parts which are related to the ABI and remove the
234 # parts which are related to the platform:
235 # - linux: '.cpython-310-x86_64-linux-gnu.so' => cp310
236 # - mac: '.cpython-310-darwin.so' => cp310
237 # - win: '.cp310-win_amd64.pyd' => cp310
238 # - win: '.pyd' => cp37 (uses _cpython_abis())
239 # - pypy: '.pypy38-pp73-x86_64-linux-gnu.so' => pypy38_pp73
240 # - graalpy: '.graalpy-38-native-x86_64-darwin.dylib'
241 # => graalpy_38_native
243 ext_suffix
= _get_config_var("EXT_SUFFIX", warn
=True)
244 if not isinstance(ext_suffix
, str) or ext_suffix
[0] != ".":
245 raise SystemError("invalid sysconfig.get_config_var('EXT_SUFFIX')")
246 parts
= ext_suffix
.split(".")
248 # CPython3.7 and earlier uses ".pyd" on Windows.
249 return _cpython_abis(sys
.version_info
[:2])
251 if soabi
.startswith("cpython"):
253 abi
= "cp" + soabi
.split("-")[1]
254 elif soabi
.startswith("cp"):
256 abi
= soabi
.split("-")[0]
257 elif soabi
.startswith("pypy"):
258 abi
= "-".join(soabi
.split("-")[:2])
259 elif soabi
.startswith("graalpy"):
260 abi
= "-".join(soabi
.split("-")[:3])
262 # pyston, ironpython, others?
266 return [_normalize_string(abi
)]
270 interpreter
: Optional
[str] = None,
271 abis
: Optional
[Iterable
[str]] = None,
272 platforms
: Optional
[Iterable
[str]] = None,
277 Yields the tags for a generic interpreter.
280 - <interpreter>-<abi>-<platform>
282 The "none" ABI will be added if it was not explicitly provided.
285 interp_name
= interpreter_name()
286 interp_version
= interpreter_version(warn
=warn
)
287 interpreter
= "".join([interp_name
, interp_version
])
289 abis
= _generic_abi()
292 platforms
= list(platforms
or platform_tags())
293 if "none" not in abis
:
296 for platform_
in platforms
:
297 yield Tag(interpreter
, abi
, platform_
)
300 def _py_interpreter_range(py_version
: PythonVersion
) -> Iterator
[str]:
302 Yields Python versions in descending order.
304 After the latest version, the major-only version will be yielded, and then
305 all previous versions of that major version.
307 if len(py_version
) > 1:
308 yield f
"py{_version_nodot(py_version[:2])}"
309 yield f
"py{py_version[0]}"
310 if len(py_version
) > 1:
311 for minor
in range(py_version
[1] - 1, -1, -1):
312 yield f
"py{_version_nodot((py_version[0], minor))}"
316 python_version
: Optional
[PythonVersion
] = None,
317 interpreter
: Optional
[str] = None,
318 platforms
: Optional
[Iterable
[str]] = None,
321 Yields the sequence of tags that are compatible with a specific version of Python.
324 - py*-none-<platform>
325 - <interpreter>-none-any # ... if `interpreter` is provided.
328 if not python_version
:
329 python_version
= sys
.version_info
[:2]
330 platforms
= list(platforms
or platform_tags())
331 for version
in _py_interpreter_range(python_version
):
332 for platform_
in platforms
:
333 yield Tag(version
, "none", platform_
)
335 yield Tag(interpreter
, "none", "any")
336 for version
in _py_interpreter_range(python_version
):
337 yield Tag(version
, "none", "any")
340 def _mac_arch(arch
: str, is_32bit
: bool = _32_BIT_INTERPRETER
) -> str:
344 if arch
.startswith("ppc"):
350 def _mac_binary_formats(version
: MacVersion
, cpu_arch
: str) -> List
[str]:
352 if cpu_arch
== "x86_64":
353 if version
< (10, 4):
355 formats
.extend(["intel", "fat64", "fat32"])
357 elif cpu_arch
== "i386":
358 if version
< (10, 4):
360 formats
.extend(["intel", "fat32", "fat"])
362 elif cpu_arch
== "ppc64":
363 # TODO: Need to care about 32-bit PPC for ppc64 through 10.2?
364 if version
> (10, 5) or version
< (10, 4):
366 formats
.append("fat64")
368 elif cpu_arch
== "ppc":
369 if version
> (10, 6):
371 formats
.extend(["fat32", "fat"])
373 if cpu_arch
in {"arm64", "x86_64"}
:
374 formats
.append("universal2")
376 if cpu_arch
in {"x86_64", "i386", "ppc64", "ppc", "intel"}
:
377 formats
.append("universal")
383 version
: Optional
[MacVersion
] = None, arch
: Optional
[str] = None
386 Yields the platform tags for a macOS system.
388 The `version` parameter is a two-item tuple specifying the macOS version to
389 generate platform tags for. The `arch` parameter is the CPU architecture to
390 generate platform tags for. Both parameters default to the appropriate value
391 for the current system.
393 version_str
, _
, cpu_arch
= platform
.mac_ver()
395 version
= cast("MacVersion", tuple(map(int, version_str
.split(".")[:2])))
396 if version
== (10, 16):
397 # When built against an older macOS SDK, Python will report macOS 10.16
398 # instead of the real version.
399 version_str
= subprocess
.run(
404 "import platform; print(platform.mac_ver()[0])",
407 env
={"SYSTEM_VERSION_COMPAT": "0"}
,
408 stdout
=subprocess
.PIPE
,
409 universal_newlines
=True,
411 version
= cast("MacVersion", tuple(map(int, version_str
.split(".")[:2])))
415 arch
= _mac_arch(cpu_arch
)
419 if (10, 0) <= version
and version
< (11, 0):
420 # Prior to Mac OS 11, each yearly release of Mac OS bumped the
421 # "minor" version number. The major version was always 10.
422 for minor_version
in range(version
[1], -1, -1):
423 compat_version
= 10, minor_version
424 binary_formats
= _mac_binary_formats(compat_version
, arch
)
425 for binary_format
in binary_formats
:
426 yield "macosx_{major}_{minor}_{binary_format}".format(
427 major
=10, minor
=minor_version
, binary_format
=binary_format
430 if version
>= (11, 0):
431 # Starting with Mac OS 11, each yearly release bumps the major version
432 # number. The minor versions are now the midyear updates.
433 for major_version
in range(version
[0], 10, -1):
434 compat_version
= major_version
, 0
435 binary_formats
= _mac_binary_formats(compat_version
, arch
)
436 for binary_format
in binary_formats
:
437 yield "macosx_{major}_{minor}_{binary_format}".format(
438 major
=major_version
, minor
=0, binary_format
=binary_format
441 if version
>= (11, 0):
442 # Mac OS 11 on x86_64 is compatible with binaries from previous releases.
443 # Arm64 support was introduced in 11.0, so no Arm binaries from previous
446 # However, the "universal2" binary format can have a
447 # macOS version earlier than 11.0 when the x86_64 part of the binary supports
448 # that version of macOS.
450 for minor_version
in range(16, 3, -1):
451 compat_version
= 10, minor_version
452 binary_formats
= _mac_binary_formats(compat_version
, arch
)
453 for binary_format
in binary_formats
:
454 yield "macosx_{major}_{minor}_{binary_format}".format(
455 major
=compat_version
[0],
456 minor
=compat_version
[1],
457 binary_format
=binary_format
,
460 for minor_version
in range(16, 3, -1):
461 compat_version
= 10, minor_version
462 binary_format
= "universal2"
463 yield "macosx_{major}_{minor}_{binary_format}".format(
464 major
=compat_version
[0],
465 minor
=compat_version
[1],
466 binary_format
=binary_format
,
470 def _linux_platforms(is_32bit
: bool = _32_BIT_INTERPRETER
) -> Iterator
[str]:
471 linux
= _normalize_string(sysconfig
.get_platform())
473 if linux
== "linux_x86_64":
475 elif linux
== "linux_aarch64":
476 linux
= "linux_armv7l"
477 _
, arch
= linux
.split("_", 1)
478 yield from _manylinux
.platform_tags(linux
, arch
)
479 yield from _musllinux
.platform_tags(arch
)
483 def _generic_platforms() -> Iterator
[str]:
484 yield _normalize_string(sysconfig
.get_platform())
487 def platform_tags() -> Iterator
[str]:
489 Provides the platform tags for this installation.
491 if platform
.system() == "Darwin":
492 return mac_platforms()
493 elif platform
.system() == "Linux":
494 return _linux_platforms()
496 return _generic_platforms()
499 def interpreter_name() -> str:
501 Returns the name of the running interpreter.
503 Some implementations have a reserved, two-letter abbreviation which will
504 be returned when appropriate.
506 name
= sys
.implementation
.name
507 return INTERPRETER_SHORT_NAMES
.get(name
) or name
510 def interpreter_version(*, warn
: bool = False) -> str:
512 Returns the version of the running interpreter.
514 version
= _get_config_var("py_version_nodot", warn
=warn
)
516 version
= str(version
)
518 version
= _version_nodot(sys
.version_info
[:2])
522 def _version_nodot(version
: PythonVersion
) -> str:
523 return "".join(map(str, version
))
526 def sys_tags(*, warn
: bool = False) -> Iterator
[Tag
]:
528 Returns the sequence of tag triples for the running interpreter.
530 The order of the sequence corresponds to priority order for the
531 interpreter, from most to least important.
534 interp_name
= interpreter_name()
535 if interp_name
== "cp":
536 yield from cpython_tags(warn
=warn
)
538 yield from generic_tags()
540 if interp_name
== "pp":
542 elif interp_name
== "cp":
543 interp
= "cp" + interpreter_version(warn
=warn
)
546 yield from compatible_tags(interpreter
=interp
)