• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

pantsbuild / pants / 19666581255

25 Nov 2025 10:36AM UTC coverage: 80.289% (+0.001%) from 80.288%
19666581255

Pull #22910

github

web-flow
Merge d496aebe4 into 7c08ed5e3
Pull Request #22910: Forwarded the `style` and `complete-platform` args from pants.toml to PEX

84 of 102 new or added lines in 7 files covered. (82.35%)

1 existing line in 1 file now uncovered.

78466 of 97729 relevant lines covered (80.29%)

3.36 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

86.09
/src/python/pants/backend/python/subsystems/setup.py
1
# Copyright 2014 Pants project contributors (see CONTRIBUTORS.md).
2
# Licensed under the Apache License, Version 2.0 (see LICENSE).
3

4
from __future__ import annotations
12✔
5

6
import enum
12✔
7
import logging
12✔
8
import os
12✔
9
from collections.abc import Iterable
12✔
10
from typing import TypeVar, cast
12✔
11

12
from packaging.utils import canonicalize_name
12✔
13

14
from pants.core.goals.generate_lockfiles import UnrecognizedResolveNamesError
12✔
15
from pants.option.errors import OptionsError
12✔
16
from pants.option.option_types import (
12✔
17
    BoolOption,
18
    DictOption,
19
    EnumOption,
20
    FileOption,
21
    StrListOption,
22
    StrOption,
23
)
24
from pants.option.subsystem import Subsystem
12✔
25
from pants.util.docutil import bin_name, doc_url
12✔
26
from pants.util.memo import memoized_method, memoized_property
12✔
27
from pants.util.strutil import softwrap
12✔
28

29
logger = logging.getLogger(__name__)
12✔
30

31

32
@enum.unique
12✔
33
class InvalidLockfileBehavior(enum.Enum):
12✔
34
    error = "error"
12✔
35
    ignore = "ignore"
12✔
36
    warn = "warn"
12✔
37

38

39
@enum.unique
12✔
40
class LockfileGenerator(enum.Enum):
12✔
41
    PEX = "pex"
12✔
42
    POETRY = "poetry"
12✔
43

44

45
RESOLVE_OPTION_KEY__DEFAULT = "__default__"
12✔
46

47
_T = TypeVar("_T")
12✔
48

49

50
class PythonSetup(Subsystem):
12✔
51
    options_scope = "python"
12✔
52
    help = "Options for Pants's Python backend."
12✔
53

54
    default_interpreter_universe = [
12✔
55
        "2.7",
56
        "3.5",
57
        "3.6",
58
        "3.7",
59
        "3.8",
60
        "3.9",
61
        "3.10",
62
        "3.11",
63
        "3.12",
64
        "3.13",
65
    ]
66

67
    _interpreter_constraints = StrListOption(
12✔
68
        default=None,
69
        help=softwrap(
70
            """
71
            The Python interpreters your codebase is compatible with.
72

73
            These constraints are used as the default value for the `interpreter_constraints`
74
            field of Python targets.
75

76
            Specify with requirement syntax, e.g. `'CPython>=2.7,<3'` (A CPython interpreter with
77
            version >=2.7 AND version <3) or `'PyPy'` (A pypy interpreter of any version). Multiple
78
            constraint strings will be ORed together.
79
            """
80
        ),
81
        metavar="<requirement>",
82
    )
83

84
    warn_on_python2_usage = BoolOption(
12✔
85
        default=True,
86
        advanced=True,
87
        help=softwrap(
88
            """\
89
            True if Pants should generate a deprecation warning when Python 2.x is used in interpreter constraints.
90

91
            As of Pants v2.24.x and later, Pants will no longer be tested regularly with Python 2.7.x. As such, going
92
            forward, Pants may or may not work with Python 2.7. This option allows disabling the deprecation
93
            warning announcing this policy change.
94
            """
95
        ),
96
    )
97

98
    @memoized_property
12✔
99
    def interpreter_constraints(self) -> tuple[str, ...]:
12✔
100
        if not self._interpreter_constraints:
1✔
101
            # TODO: This is a hacky affordance for Pants's own tests, dozens of which were
102
            #  written when Pants provided default ICs, and implicitly rely on that assumption.
103
            #  We'll probably want to find and modify all those tests to set an explicit IC, but
104
            #  that will take time.
105
            if "PYTEST_CURRENT_TEST" in os.environ:
×
106
                return (">=3.9,<3.15",)
×
107
            raise OptionsError(
×
108
                softwrap(
109
                    f"""\
110
                    You must explicitly specify the default Python interpreter versions your code
111
                    is intended to run against.
112

113
                    You specify these interpreter constraints using the `interpreter_constraints`
114
                    option in the `[python]` section of pants.toml.
115

116
                    We recommend constraining to a single interpreter minor version if you can,
117
                    e.g., `interpreter_constraints = ['==3.11.*']`, or at least a small number of
118
                    interpreter minor versions, e.g., `interpreter_constraints = ['>=3.10,<3.12']`.
119

120
                    Individual targets can override these default interpreter constraints,
121
                    if different parts of your codebase run against different python interpreter
122
                    versions in a single repo.
123

124
                    See {doc_url("docs/python/overview/interpreter-compatibility")} for details.
125
                    """
126
                ),
127
            )
128

129
        # Warn if Python 2.x is still in use. This warning should only be displayed once since this
130
        # function is memoized.
131
        if self.warn_on_python2_usage:
1✔
132
            # Side-step import cycle.
133
            from pants.backend.python.util_rules.interpreter_constraints import (
×
134
                warn_on_python2_usage_in_interpreter_constraints,
135
            )
136

137
            warn_on_python2_usage_in_interpreter_constraints(
×
138
                self._interpreter_constraints,
139
                description_of_origin="the `[python].interpreter_constraints` option",
140
            )
141

142
        return self._interpreter_constraints
1✔
143

144
    interpreter_versions_universe = StrListOption(
12✔
145
        default=default_interpreter_universe,
146
        help=softwrap(
147
            f"""
148
            All known Python major/minor interpreter versions that may be used by either
149
            your code or tools used by your code.
150

151
            This is used by Pants to robustly handle interpreter constraints, such as knowing
152
            when generating lockfiles which Python versions to check if your code is using.
153

154
            This does not control which interpreter your code will use. Instead, to set your
155
            interpreter constraints, update `[python].interpreter_constraints`, the
156
            `interpreter_constraints` field, and relevant tool options like
157
            `[isort].interpreter_constraints` to tell Pants which interpreters your code
158
            actually uses. See {doc_url("docs/python/overview/interpreter-compatibility")}.
159

160
            All elements must be the minor and major Python version, e.g. `'2.7'` or `'3.10'`. Do
161
            not include the patch version.
162
            """
163
        ),
164
        advanced=True,
165
    )
166
    enable_resolves = BoolOption(
12✔
167
        default=False,
168
        help=softwrap(
169
            """
170
            Set to true to enable lockfiles for user code. See `[python].resolves` for an
171
            explanation of this feature.
172

173
            This option is mutually exclusive with `[python].requirement_constraints`. We strongly
174
            recommend using this option because it:
175

176
              1. Uses `--hash` to validate that all downloaded files are expected, which reduces\
177
                the risk of supply chain attacks.
178
              2. Enforces that all transitive dependencies are in the lockfile, whereas\
179
                constraints allow you to leave off dependencies. This ensures your build is more\
180
                stable and reduces the risk of supply chain attacks.
181
              3. Allows you to have multiple lockfiles in your repository.
182
            """
183
        ),
184
        advanced=True,
185
        mutually_exclusive_group="lockfile",
186
    )
187
    resolves = DictOption[str](
12✔
188
        default={"python-default": "3rdparty/python/default.lock"},
189
        help=softwrap(
190
            f"""
191
            A mapping of logical names to lockfile paths used in your project.
192

193
            Many organizations only need a single resolve for their whole project, which is
194
            a good default and often the simplest thing to do. However, you may need multiple
195
            resolves, such as if you use two conflicting versions of a requirement in
196
            your repository.
197

198
            If you only need a single resolve, run `{bin_name()} generate-lockfiles` to
199
            generate the lockfile.
200

201
            If you need multiple resolves:
202

203
              1. Via this option, define multiple resolve names and their lockfile paths.\
204
                The names should be meaningful to your repository, such as `data-science` or\
205
                `pants-plugins`.
206
              2. Set the default with `[python].default_resolve`.
207
              3. Update your `python_requirement` targets with the `resolve` field to declare which\
208
                resolve they should be available in. They default to `[python].default_resolve`,\
209
                so you only need to update targets that you want in non-default resolves.\
210
                (Often you'll set this via the `python_requirements` or `poetry_requirements`\
211
                target generators)
212
              4. Run `{bin_name()} generate-lockfiles` to generate the lockfiles. If the results\
213
                aren't what you'd expect, adjust the prior step.
214
              5. Update any targets like `python_source` / `python_sources`,\
215
                `python_test` / `python_tests`, and `pex_binary` which need to set a non-default\
216
                resolve with the `resolve` field.
217

218
            If a target can work with multiple resolves, you can either use the `parametrize`
219
            mechanism or manually create a distinct target per resolve. See {doc_url("docs/using-pants/key-concepts/targets-and-build-files")}
220
            for information about `parametrize`.
221

222
            For example:
223

224
                python_sources(
225
                    resolve=parametrize("data-science", "web-app"),
226
                )
227

228
            You can name the lockfile paths what you would like; Pants does not expect a
229
            certain file extension or location.
230

231
            Only applies if `[python].enable_resolves` is true.
232
            """
233
        ),
234
        advanced=True,
235
    )
236
    default_resolve = StrOption(
12✔
237
        default="python-default",
238
        help=softwrap(
239
            """
240
            The default value used for the `resolve` field.
241

242
            The name must be defined as a resolve in `[python].resolves`.
243
            """
244
        ),
245
        advanced=True,
246
    )
247

248
    _default_to_resolve_interpreter_constraints = BoolOption(
12✔
249
        default=False,
250
        help=softwrap(
251
            """
252
            For Python targets with both `resolve` and `interpreter_constraints` fields, default to using the `interpreter_constraints` field of the resolve if `interpreter_constraints` is not set on the target itself.
253

254
            `[python].enable_resolves` must be `True` for this option to also be enabled. This will become True by default in a future version of Pants and eventually be deprecated and then removed.
255
            """
256
        ),
257
        advanced=True,
258
    )
259

260
    @memoized_property
12✔
261
    def default_to_resolve_interpreter_constraints(self) -> bool:
12✔
262
        if self._default_to_resolve_interpreter_constraints and not self.enable_resolves:
1✔
263
            raise OptionsError(
×
264
                softwrap(
265
                    """
266
                You cannot set `[python].default_to_resolve_interpreter_constraints = true` without setting `[python].enable_resolves = true`.
267

268
                Please either enable resolves or set `[python].default_to_resolve_interpreter_constraints = false` (the default setting).
269
                """
270
                )
271
            )
272
        return self._default_to_resolve_interpreter_constraints
1✔
273

274
    separate_lockfile_metadata_file = BoolOption(
12✔
275
        advanced=True,
276
        default=False,
277
        help=softwrap(
278
            """
279
            If set, lockfile metadata will be written to a separate sibling file, rather than
280
            prepended as a header to the lockfile (which has various disadvantages).
281
            This will soon become True by default and eventually the header option will be
282
            deprecated and then removed.
283
            """
284
        ),
285
    )
286
    default_run_goal_use_sandbox = BoolOption(
12✔
287
        default=True,
288
        help=softwrap(
289
            """
290
            The default value used for the `run_goal_use_sandbox` field of Python targets. See the
291
            relevant field for more details.
292
            """
293
        ),
294
    )
295
    pip_version = StrOption(
12✔
296
        default="24.2",
297
        help=softwrap(
298
            f"""
299
            Use this version of Pip for resolving requirements and generating lockfiles.
300

301
            The value used here must be one of the Pip versions supported by the underlying PEX
302
            version. See {doc_url("docs/python/overview/pex")} for details.
303

304
            N.B.: The `latest` value selects the latest of the choices listed by PEX which is not
305
            necessarily the latest Pip version released on PyPI.
306
            """
307
        ),
308
        advanced=True,
309
    )
310
    _resolves_to_interpreter_constraints = DictOption[list[str]](
12✔
311
        help=softwrap(
312
            """
313
            Override the interpreter constraints to use when generating a resolve's lockfile
314
            with the `generate-lockfiles` goal.
315

316
            By default, each resolve from `[python].resolves` will use your
317
            global interpreter constraints set in `[python].interpreter_constraints`. With
318
            this option, you can override each resolve to use certain interpreter
319
            constraints, such as `{'data-science': ['==3.8.*']}`.
320

321
            Warning: this does NOT impact the interpreter constraints used by targets within the
322
            resolve, which is instead set by the option `[python].interpreter_constraints` and the
323
            `interpreter_constraints` field. It only impacts how the lockfile is generated.
324

325
            Pants will validate that the interpreter constraints of your code using a
326
            resolve are compatible with that resolve's own constraints. For example, if your
327
            code is set to use `['==3.9.*']` via the `interpreter_constraints` field, but it's
328
            using a resolve whose interpreter constraints are set to `['==3.7.*']`, then
329
            Pants will error explaining the incompatibility.
330

331
            The keys must be defined as resolves in `[python].resolves`.
332
            """
333
        ),
334
        advanced=True,
335
    )
336
    _resolves_to_constraints_file = DictOption[str](
12✔
337
        help=softwrap(
338
            f"""
339
            When generating a resolve's lockfile, use a constraints file to pin the version of
340
            certain requirements. This is particularly useful to pin the versions of transitive
341
            dependencies of your direct requirements.
342

343
            See https://pip.pypa.io/en/stable/user_guide/#constraints-files for more information on
344
            the format of constraint files and how constraints are applied in Pex and pip.
345

346
            Expects a dictionary of resolve names from `[python].resolves` and Python tools (e.g.
347
            `black` and `pytest`) to file paths for
348
            constraints files. For example,
349
            `{{'data-science': '3rdparty/data-science-constraints.txt'}}`.
350
            If a resolve is not set in the dictionary, it will not use a constraints file.
351

352
            You can use the key `{RESOLVE_OPTION_KEY__DEFAULT}` to set a default value for all
353
            resolves.
354
            """
355
        ),
356
        advanced=True,
357
    )
358
    _resolves_to_no_binary = DictOption[list[str]](
12✔
359
        help=softwrap(
360
            f"""
361
            When generating a resolve's lockfile, do not use binary packages (i.e. wheels) for
362
            these 3rdparty project names.
363

364
            Expects a dictionary of resolve names from `[python].resolves` and Python tools (e.g.
365
            `black` and `pytest`) to lists of project names. For example,
366
            `{{'data-science': ['requests', 'numpy']}}`. If a resolve is not set in the dictionary,
367
            it will have no restrictions on binary packages.
368

369
            You can use the key `{RESOLVE_OPTION_KEY__DEFAULT}` to set a default value for all
370
            resolves.
371

372
            For each resolve, you can also use the value `:all:` to disable all binary packages:
373
            `{{'data-science': [':all:']}}`.
374

375
            Note that some packages are tricky to compile and may fail to install when this option
376
            is used on them. See https://pip.pypa.io/en/stable/cli/pip_install/#install-no-binary
377
            for details.
378
            """
379
        ),
380
        advanced=True,
381
    )
382
    _resolves_to_only_binary = DictOption[list[str]](
12✔
383
        help=softwrap(
384
            f"""
385
            When generating a resolve's lockfile, do not use source packages (i.e. sdists) for
386
            these 3rdparty project names, e.g `['django', 'requests']`.
387

388
            Expects a dictionary of resolve names from `[python].resolves` and Python tools (e.g.
389
            `black` and `pytest`) to lists of project names. For example,
390
            `{{'data-science': ['requests', 'numpy']}}`. If a resolve is not set in the dictionary,
391
            it will have no restrictions on source packages.
392

393
            You can use the key `{RESOLVE_OPTION_KEY__DEFAULT}` to set a default value for all
394
            resolves.
395

396
            For each resolve you can use the value `:all:` to disable all source packages:
397
            `{{'data-science': [':all:']}}`.
398

399
            Packages without binary distributions will fail to install when this option is used on
400
            them. See https://pip.pypa.io/en/stable/cli/pip_install/#install-only-binary for
401
            details.
402
            """
403
        ),
404
        advanced=True,
405
    )
406
    _resolves_to_excludes = DictOption[list[str]](
12✔
407
        help=softwrap(
408
            """ Specifies requirements to exclude from a resolve and its
409
            lockfile.  Any distribution included in the PEX's resolve that
410
            matches the requirement is excluded from the built PEX along with
411
            all of its transitive dependencies that are not also required by
412
            other non-excluded distributions.  At runtime, the PEX will boot
413
            without checking the excluded dependencies are available.
414
            """
415
        ),
416
        advanced=True,
417
    )
418
    _resolves_to_overrides = DictOption[list[str]](
12✔
419
        help=softwrap(
420
            """ Specifies a transitive requirement to override in a resolve
421
            and its lockfile.  Overrides can either modify an existing
422
            dependency on a project name by changing extras, version
423
            constraints or markers or else they can completely swap out the
424
            dependency for a dependency on another project altogether. For the
425
            former, simply supply the requirement you wish. For example,
426
            specifying `--override cowsay==5.0` will override any transitive
427
            dependency on cowsay that has any combination of extras, version
428
            constraints or markers with the requirement `cowsay==5.0`. To
429
            completely replace cowsay with another library altogether, you can
430
            specify an override like `--override cowsay=my-cowsay>2`. This
431
            will replace any transitive dependency on cowsay that has any
432
            combination of extras, version constraints or markers with the
433
            requirement `my-cowsay>2`."""
434
        ),
435
        advanced=True,
436
    )
437

438
    _resolves_to_sources = DictOption[list[str]](
12✔
439
        help=softwrap(""" Defines a limited scope to use a named find links repo or
440
            index for specific dependencies in a resolve and its lockfile.
441
            Sources take the form `<name>=<scope>` where the name must match
442
            a find links repo or index defined via `[python-repos].indexes` or
443
            `[python-repos].find_links`. The scope can be a project name
444
            (e.g., `internal=torch` to resolve the `torch` project from the
445
            `internal` repo), a project name with a marker (e.g.,
446
            `internal=torch; sys_platform != 'darwin'` to resolve `torch` from
447
            the `internal` repo except on macOS), or just a marker (e.g.,
448
            `piwheels=platform_machine == 'armv7l'` to resolve from the
449
            `piwheels` repo when targeting 32bit ARM machines)."""),
450
        advanced=True,
451
    )
452

453
    _resolves_to_lock_style = DictOption[str](
12✔
454
        help=softwrap(
455
            f"""
456
            The style of lock to generate. The 'strict' style generates a lock file that contains exactly the
457
            distributions that would be used in a local PEX build. If an sdist would be used, the sdist is included, but if a
458
            wheel would be used, an accompanying sdist will not be included. The 'sources' style includes locks containing both
459
            wheels and the associated sdists when available. The 'universal' style generates a universal lock for all possible
460
            target interpreters and platforms, although the scope can be constrained via one or more --interpreter-constraint. Of
461
            the three lock styles, only 'strict' can give you full confidence in the lock since it includes exactly the artifacts
462
            that are included in the local PEX you'll build to test the lock result with before checking in the lock. With the
463
            other two styles you lock un-vetted artifacts in addition to the 'strict' ones; so, even though you can be sure to
464
            reproducibly resolve those same un-vetted artifacts in the future, they're still un-vetted and could be innocently or
465
            maliciously different from the 'strict' artifacts you can locally vet before committing the lock to version control.
466
            The effects of the differences could range from failing a resolve using the lock when the un-vetted artifacts have
467
            different dependencies from their sibling artifacts, to your application crashing due to different code in the sibling
468
            artifacts to being compromised by differing code in the sibling artifacts. So, although the more permissive lock
469
            styles will allow the lock to work on a wider range of machines /are apparently more convenient, the convenience comes
470
            with a potential price and using these styles should be considered carefully.
471

472
            Expects a dictionary of resolve names from `[python].resolves` to style values.
473
            For example, `{{'data-science': 'strict', 'web-app': 'universal'}}`.
474
            If a resolve is not set in the dictionary, it will default to 'universal'.
475

476
            You can use the key `{RESOLVE_OPTION_KEY__DEFAULT}` to set a default value for all
477
            resolves.
478

479
            See https://docs.pex-tool.org/api/pex.html for more information on lockfile styles.
480
            """
481
        ),
482
        advanced=True,
483
    )
484

485
    _resolves_to_complete_platforms = DictOption[list[str]](
12✔
486
        help=softwrap(
487
            f"""
488
            The platforms the built PEX should be compatible with when generating lockfiles.
489

490
            Complete platforms allow you to create lockfiles for specific target platforms
491
            (e.g., different CPU architectures or operating systems) rather than the default
492
            universal platforms. This is particularly useful for cross-platform builds or
493
            when you need strict platform-specific dependencies.
494

495
            You can give a list of multiple complete platforms to create a multiplatform lockfile,
496
            meaning that the lockfile will include wheels for all of the supported environments.
497

498
            Expects a dictionary of resolve names from `[python].resolves` to lists of addresses of
499
            `file` or `resource` targets that point to files containing complete platform JSON as
500
            described by Pex (https://pex.readthedocs.io/en/latest/buildingpex.html#complete-platform).
501

502
            For example:
503
            `{{'python-default': ['3rdparty/platforms:linux_aarch64', '3rdparty/platforms:macos_arm64']}}`.
504

505
            You can use the key `{RESOLVE_OPTION_KEY__DEFAULT}` to set a default value for all
506
            resolves.
507

508
            Complete platform JSON files can be generated using PEX's interpreter inspect command on
509
            the target platform: `pex3 interpreter inspect --markers --tags > platform.json`
510

511
            See https://docs.pex-tool.org for more information.
512
            """
513
        ),
514
        advanced=True,
515
    )
516

517
    invalid_lockfile_behavior = EnumOption(
12✔
518
        default=InvalidLockfileBehavior.error,
519
        help=softwrap(
520
            """
521
            The behavior when a lockfile has requirements or interpreter constraints that are
522
            not compatible with what the current build is using.
523

524
            We recommend keeping the default of `error` for CI builds.
525

526
            Note that `warn` will still expect a Pants lockfile header, it only won't error if
527
            the lockfile is stale and should be regenerated.
528

529
            Use `ignore` to avoid needing a lockfile header at all, e.g. if you are manually
530
            managing lockfiles rather than using the `generate-lockfiles` goal.
531
            """
532
        ),
533
        advanced=True,
534
    )
535
    resolves_generate_lockfiles = BoolOption(
12✔
536
        default=True,
537
        help=softwrap(
538
            """
539
            If False, Pants will not attempt to generate lockfiles for `[python].resolves` when
540
            running the `generate-lockfiles` goal.
541

542
            This is intended to allow you to manually generate lockfiles for your own code,
543
            rather than using Pex lockfiles. For example, when adopting Pants in a project already
544
            using Poetry, you can use `poetry export --dev` to create a requirements.txt-style
545
            lockfile understood by Pants, then point `[python].resolves` to the file.
546

547
            If you set this to False, Pants will not attempt to validate the metadata headers
548
            for your user lockfiles. This is useful so that you can keep
549
            `[python].invalid_lockfile_behavior` to `error` or `warn` if you'd like so that tool
550
            lockfiles continue to be validated, while user lockfiles are skipped.
551

552
            Warning: it will likely be slower to install manually generated user lockfiles than Pex
553
            ones because Pants cannot as efficiently extract the subset of requirements used for a
554
            particular task. See the option `[python].run_against_entire_lockfile`.
555
            """
556
        ),
557
        advanced=True,
558
    )
559
    run_against_entire_lockfile = BoolOption(
12✔
560
        default=False,
561
        help=softwrap(
562
            """
563
            If enabled, when running binaries, tests, and repls, Pants will use the entire
564
            lockfile file instead of just the relevant subset.
565

566
            If you are using Pex lockfiles, we generally do not recommend this. You will already
567
            get similar performance benefits to this option, without the downsides.
568

569
            Otherwise, this option can improve performance and reduce cache size.
570
            But it has two consequences:
571
            1) All cached test results will be invalidated if any requirement in the lockfile
572
               changes, rather than just those that depend on the changed requirement.
573
            2) Requirements unneeded by a test/run/repl will be present on the sys.path, which
574
               might in rare cases cause their behavior to change.
575

576
            This option does not affect packaging deployable artifacts, such as
577
            PEX files, wheels and cloud functions, which will still use just the exact
578
            subset of requirements needed.
579
            """
580
        ),
581
        advanced=True,
582
    )
583

584
    __constraints_deprecation_msg = softwrap(
12✔
585
        f"""
586
        We encourage instead migrating to `[python].enable_resolves` and `[python].resolves`,
587
        which is an improvement over this option. The `[python].resolves` feature ensures that
588
        your lockfiles are fully comprehensive, i.e. include all transitive dependencies;
589
        uses hashes for better supply chain security; and supports advanced features like VCS
590
        and local requirements, along with options `[python].resolves_to_only_binary`.
591

592
        To migrate, stop setting `[python].requirement_constraints` and
593
        `[python].resolve_all_constraints`, and instead set `[python].enable_resolves` to
594
        `true`. Then, run `{bin_name()} generate-lockfiles`.
595
        """
596
    )
597
    requirement_constraints = FileOption(
12✔
598
        default=None,
599
        help=softwrap(
600
            """
601
            When resolving third-party requirements for your own code (vs. tools you run),
602
            use this constraints file to determine which versions to use.
603

604
            Mutually exclusive with `[python].enable_resolves`, which we generally recommend as an
605
            improvement over constraints file.
606

607
            See https://pip.pypa.io/en/stable/user_guide/#constraints-files for more
608
            information on the format of constraint files and how constraints are applied in
609
            Pex and pip.
610

611
            This only applies when resolving user requirements, rather than tools you run
612
            like Black and Pytest. To constrain tools, set `[tool].lockfile`, e.g.
613
            `[black].lockfile`.
614
            """
615
        ),
616
        advanced=True,
617
        mutually_exclusive_group="lockfile",
618
        removal_version="3.0.0.dev0",
619
        removal_hint=__constraints_deprecation_msg,
620
    )
621
    _resolve_all_constraints = BoolOption(
12✔
622
        default=True,
623
        help=softwrap(
624
            """
625
            (Only relevant when using `[python].requirement_constraints.`) If enabled, when
626
            resolving requirements, Pants will first resolve your entire
627
            constraints file as a single global resolve. Then, if the code uses a subset of
628
            your constraints file, Pants will extract the relevant requirements from that
629
            global resolve so that only what's actually needed gets used. If disabled, Pants
630
            will not use a global resolve and will resolve each subset of your requirements
631
            independently.
632

633
            Usually this option should be enabled because it can result in far fewer resolves.
634
            """
635
        ),
636
        advanced=True,
637
        removal_version="3.0.0.dev0",
638
        removal_hint=__constraints_deprecation_msg,
639
    )
640
    resolver_manylinux = StrOption(
12✔
641
        default="manylinux2014",
642
        help=softwrap(
643
            """
644
            Whether to allow resolution of manylinux wheels when resolving requirements for
645
            foreign linux platforms. The value should be a manylinux platform upper bound,
646
            e.g. `'manylinux2010'`, or else the string `'no'` to disallow.
647
            """
648
        ),
649
        advanced=True,
650
    )
651

652
    tailor_source_targets = BoolOption(
12✔
653
        default=True,
654
        help=softwrap(
655
            """
656
            If true, add `python_sources`, `python_tests`, and `python_test_utils` targets with
657
            the `tailor` goal."""
658
        ),
659
        advanced=True,
660
    )
661
    tailor_ignore_empty_init_files = BoolOption(
12✔
662
        "--tailor-ignore-empty-init-files",
663
        default=True,
664
        help=softwrap(
665
            """
666
            If true, don't add `python_sources` targets for `__init__.py` files that are both empty
667
            and where there are no other Python files in the directory.
668

669
            Empty and solitary `__init__.py` files usually exist as import scaffolding rather than
670
            true library code, so it can be noisy to add BUILD files.
671

672
            Even if this option is set to true, Pants will still ensure the empty `__init__.py`
673
            files are included in the sandbox when running processes.
674

675
            If you set to false, you may also want to set `[python-infer].init_files = "always"`.
676
            """
677
        ),
678
        advanced=True,
679
    )
680
    tailor_requirements_targets = BoolOption(
12✔
681
        default=True,
682
        help=softwrap(
683
            """
684
            If true, add `python_requirements`, `poetry_requirements`, and `pipenv_requirements`
685
            target generators with the `tailor` goal.
686

687
            `python_requirements` targets are added for any file that matches the pattern
688
            `*requirements*.txt`. You will need to manually add `python_requirements` for different
689
            file names like `reqs.txt`.
690

691
            `poetry_requirements` targets are added for `pyproject.toml` files with `[tool.poetry`
692
            in them.
693
            """
694
        ),
695
        advanced=True,
696
    )
697
    tailor_pex_binary_targets = BoolOption(
12✔
698
        default=False,
699
        help=softwrap(
700
            """
701
            If true, add `pex_binary` targets for Python files named `__main__.py` or with a
702
            `__main__` clause with the `tailor` goal.
703
            """
704
        ),
705
        advanced=True,
706
    )
707
    tailor_py_typed_targets = BoolOption(
12✔
708
        default=True,
709
        help=softwrap(
710
            """
711
            If true, add `resource` targets for marker files named `py.typed` with the `tailor` goal.
712
            """
713
        ),
714
        advanced=True,
715
    )
716
    macos_big_sur_compatibility = BoolOption(
12✔
717
        default=False,
718
        help=softwrap(
719
            """
720
            If set, and if running on macOS Big Sur, use `macosx_10_16` as the platform
721
            when building wheels. Otherwise, the default of `macosx_11_0` will be used.
722
            This may be required for `pip` to be able to install the resulting distribution
723
            on Big Sur.
724
            """
725
        ),
726
        advanced=True,
727
    )
728
    enable_lockfile_targets = BoolOption(
12✔
729
        default=True,
730
        help=softwrap(
731
            """
732
            Create targets for all Python lockfiles defined in `[python].resolves`.
733

734
            The lockfile targets will then be used as dependencies to the `python_requirement`
735
            targets that use them, invalidating source targets per resolve when the lockfile
736
            changes.
737

738
            If another targets address is in conflict with the created lockfile target, it will
739
            shadow the lockfile target and it will not be available as a dependency for any
740
            `python_requirement` targets.
741
            """
742
        ),
743
        advanced=True,
744
    )
745
    repl_history = BoolOption(
12✔
746
        default=True,
747
        help="Whether to use the standard Python command history file when running a repl.",
748
    )
749

750
    @property
12✔
751
    def enable_synthetic_lockfiles(self) -> bool:
12✔
752
        return self.enable_resolves and self.enable_lockfile_targets
×
753

754
    @memoized_property
12✔
755
    def resolves_to_interpreter_constraints(self) -> dict[str, tuple[str, ...]]:
12✔
756
        result = {}
2✔
757
        unrecognized_resolves = []
2✔
758
        for resolve, ics in self._resolves_to_interpreter_constraints.items():
2✔
759
            if resolve not in self.resolves:
2✔
760
                unrecognized_resolves.append(resolve)
1✔
761
            if ics and self.warn_on_python2_usage:
2✔
762
                # Side-step import cycle.
763
                from pants.backend.python.util_rules.interpreter_constraints import (
×
764
                    warn_on_python2_usage_in_interpreter_constraints,
765
                )
766

767
                warn_on_python2_usage_in_interpreter_constraints(
×
768
                    ics,
769
                    description_of_origin=f"the `[python].resolves_to_interpreter_constraints` option for resolve {resolve}",
770
                )
771

772
            result[resolve] = tuple(ics)
2✔
773
        if unrecognized_resolves:
2✔
774
            raise UnrecognizedResolveNamesError(
1✔
775
                unrecognized_resolves,
776
                self.resolves.keys(),
777
                description_of_origin="the option `[python].resolves_to_interpreter_constraints`",
778
            )
779
        return result
2✔
780

781
    def _resolves_to_option_helper(
12✔
782
        self,
783
        option_value: dict[str, _T],
784
        option_name: str,
785
    ) -> dict[str, _T]:
786
        all_valid_resolves = set(self.resolves)
1✔
787
        unrecognized_resolves = set(option_value.keys()) - {
1✔
788
            RESOLVE_OPTION_KEY__DEFAULT,
789
            *all_valid_resolves,
790
        }
791
        if unrecognized_resolves:
1✔
792
            raise UnrecognizedResolveNamesError(
1✔
793
                sorted(unrecognized_resolves),
794
                {*all_valid_resolves, RESOLVE_OPTION_KEY__DEFAULT},
795
                description_of_origin=f"the option `[python].{option_name}`",
796
            )
797
        default_val = option_value.get(RESOLVE_OPTION_KEY__DEFAULT)
1✔
798
        if not default_val:
1✔
799
            return option_value
1✔
800
        return {resolve: option_value.get(resolve, default_val) for resolve in all_valid_resolves}
1✔
801

802
    @memoized_method
12✔
803
    def resolves_to_constraints_file(self) -> dict[str, str]:
12✔
804
        return self._resolves_to_option_helper(
1✔
805
            self._resolves_to_constraints_file,
806
            "resolves_to_constraints_file",
807
        )
808

809
    @memoized_method
12✔
810
    def resolves_to_no_binary(self) -> dict[str, list[str]]:
12✔
811
        return {
1✔
812
            resolve: [canonicalize_name(v) for v in vals]
813
            for resolve, vals in self._resolves_to_option_helper(
814
                self._resolves_to_no_binary,
815
                "resolves_to_no_binary",
816
            ).items()
817
        }
818

819
    @memoized_method
12✔
820
    def resolves_to_only_binary(self) -> dict[str, list[str]]:
12✔
821
        return {
1✔
822
            resolve: sorted([canonicalize_name(v) for v in vals])
823
            for resolve, vals in self._resolves_to_option_helper(
824
                self._resolves_to_only_binary,
825
                "resolves_to_only_binary",
826
            ).items()
827
        }
828

829
    @memoized_method
12✔
830
    def resolves_to_excludes(self) -> dict[str, list[str]]:
12✔
831
        return {
×
832
            resolve: sorted(vals)
833
            for resolve, vals in self._resolves_to_option_helper(
834
                self._resolves_to_excludes,
835
                "resolves_to_excludes",
836
            ).items()
837
        }
838

839
    @memoized_method
12✔
840
    def resolves_to_overrides(self) -> dict[str, list[str]]:
12✔
841
        return {
×
842
            resolve: sorted(vals)
843
            for resolve, vals in self._resolves_to_option_helper(
844
                self._resolves_to_overrides,
845
                "resolves_to_overrides",
846
            ).items()
847
        }
848

849
    @memoized_method
12✔
850
    def resolves_to_sources(self) -> dict[str, list[str]]:
12✔
851
        return {
×
852
            resolve: sorted(vals)
853
            for resolve, vals in self._resolves_to_option_helper(
854
                self._resolves_to_sources,
855
                "resolves_to_sources",
856
            ).items()
857
        }
858

859
    @memoized_method
12✔
860
    def resolves_to_lock_style(self) -> dict[str, str]:
12✔
NEW
861
        return self._resolves_to_option_helper(
×
862
            self._resolves_to_lock_style,
863
            "resolves_to_lock_style",
864
        )
865

866
    @memoized_method
12✔
867
    def resolves_to_complete_platforms(self) -> dict[str, list[str]]:
12✔
NEW
868
        return self._resolves_to_option_helper(
×
869
            self._resolves_to_complete_platforms,
870
            "resolves_to_complete_platforms",
871
        )
872

873
    @property
12✔
874
    def manylinux(self) -> str | None:
12✔
875
        manylinux = cast(str | None, self.resolver_manylinux)
×
876
        if manylinux is None or manylinux.lower() in ("false", "no", "none"):
×
877
            return None
×
878
        return manylinux
×
879

880
    @property
12✔
881
    def resolve_all_constraints(self) -> bool:
12✔
882
        if (
1✔
883
            self._resolve_all_constraints
884
            and not self.options.is_default("resolve_all_constraints")
885
            and not self.requirement_constraints
886
        ):
887
            raise ValueError(
×
888
                softwrap(
889
                    """
890
                    `[python].resolve_all_constraints` is enabled, so
891
                    `[python].requirement_constraints` must also be set.
892
                    """
893
                )
894
            )
895
        return self._resolve_all_constraints
1✔
896

897
    @property
12✔
898
    def scratch_dir(self):
12✔
899
        return os.path.join(self.options.pants_workdir, *self.options_scope.split("."))
×
900

901
    def compatibility_or_constraints(
12✔
902
        self, compatibility: Iterable[str] | None, resolve: str | None
903
    ) -> tuple[str, ...]:
904
        """Return either the given `compatibility` field or the global interpreter constraints.
905

906
        If interpreter constraints are supplied by the CLI flag, return those only.
907
        """
908
        if self.options.is_flagged("interpreter_constraints"):
1✔
909
            return self.interpreter_constraints
×
910
        if compatibility:
1✔
911
            return tuple(compatibility)
1✔
912
        if resolve and self.default_to_resolve_interpreter_constraints:
1✔
913
            return self.resolves_to_interpreter_constraints.get(
1✔
914
                resolve, self.interpreter_constraints
915
            )
916
        return self.interpreter_constraints
1✔
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc