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

pantsbuild / pants / 24055979590

06 Apr 2026 11:17PM UTC coverage: 52.37% (-40.5%) from 92.908%
24055979590

Pull #23225

github

web-flow
Merge 67474653c into 542ca048d
Pull Request #23225: Add --test-show-all-batch-targets to expose all targets in batched pytest

6 of 17 new or added lines in 2 files covered. (35.29%)

23030 existing lines in 605 files now uncovered.

31643 of 60422 relevant lines covered (52.37%)

1.05 hits per line

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

89.38
/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
2✔
5

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

12
from packaging.utils import canonicalize_name
2✔
13

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

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

31

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

38

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

44

45
@enum.unique
2✔
46
class PexBuilder(enum.Enum):
2✔
47
    pex = "pex"
2✔
48
    uv = "uv"
2✔
49

50

51
RESOLVE_OPTION_KEY__DEFAULT = "__default__"
2✔
52

53
_T = TypeVar("_T")
2✔
54

55

56
DEFAULT_TEST_FILE_GLOBS = ("test_*.py", "*_test.py", "tests.py")
2✔
57
DEFAULT_TESTUTIL_FILE_GLOBS = ("conftest.py", "test_*.pyi", "*_test.pyi", "tests.pyi")
2✔
58

59

60
class PythonSetup(Subsystem):
2✔
61
    options_scope = "python"
2✔
62
    help = "Options for Pants's Python backend."
2✔
63

64
    default_interpreter_universe = [
2✔
65
        "2.7",
66
        "3.5",
67
        "3.6",
68
        "3.7",
69
        "3.8",
70
        "3.9",
71
        "3.10",
72
        "3.11",
73
        "3.12",
74
        "3.13",
75
        "3.14",
76
    ]
77

78
    _interpreter_constraints = StrListOption(
2✔
79
        default=None,
80
        help=softwrap(
81
            """
82
            The Python interpreters your codebase is compatible with.
83

84
            These constraints are used as the default value for the `interpreter_constraints`
85
            field of Python targets.
86

87
            Specify with requirement syntax, e.g. `'CPython>=2.7,<3'` (A CPython interpreter with
88
            version >=2.7 AND version <3) or `'PyPy'` (A pypy interpreter of any version). Multiple
89
            constraint strings will be ORed together.
90
            """
91
        ),
92
        metavar="<requirement>",
93
    )
94

95
    warn_on_python2_usage = BoolOption(
2✔
96
        default=True,
97
        advanced=True,
98
        help=softwrap(
99
            """\
100
            True if Pants should generate a deprecation warning when Python 2.x is used in interpreter constraints.
101

102
            As of Pants v2.24.x and later, Pants will no longer be tested regularly with Python 2.7.x. As such, going
103
            forward, Pants may or may not work with Python 2.7. This option allows disabling the deprecation
104
            warning announcing this policy change.
105
            """
106
        ),
107
    )
108

109
    @memoized_property
2✔
110
    def interpreter_constraints(self) -> tuple[str, ...]:
2✔
111
        if not self._interpreter_constraints:
2✔
112
            # TODO: This is a hacky affordance for Pants's own tests, dozens of which were
113
            #  written when Pants provided default ICs, and implicitly rely on that assumption.
114
            #  We'll probably want to find and modify all those tests to set an explicit IC, but
115
            #  that will take time.
116
            if "PYTEST_CURRENT_TEST" in os.environ:
2✔
117
                return (">=3.9,<3.15",)
2✔
118
            raise OptionsError(
×
119
                softwrap(
120
                    f"""\
121
                    You must explicitly specify the default Python interpreter versions your code
122
                    is intended to run against.
123

124
                    You specify these interpreter constraints using the `interpreter_constraints`
125
                    option in the `[python]` section of pants.toml.
126

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

131
                    Individual targets can override these default interpreter constraints,
132
                    if different parts of your codebase run against different python interpreter
133
                    versions in a single repo.
134

135
                    See {doc_url("docs/python/overview/interpreter-compatibility")} for details.
136
                    """
137
                ),
138
            )
139

140
        # Warn if Python 2.x is still in use. This warning should only be displayed once since this
141
        # function is memoized.
142
        if self.warn_on_python2_usage:
2✔
143
            # Side-step import cycle.
144
            from pants.backend.python.util_rules.interpreter_constraints import (
2✔
145
                warn_on_python2_usage_in_interpreter_constraints,
146
            )
147

148
            warn_on_python2_usage_in_interpreter_constraints(
2✔
149
                self._interpreter_constraints,
150
                description_of_origin="the `[python].interpreter_constraints` option",
151
            )
152

153
        return self._interpreter_constraints
2✔
154

155
    interpreter_versions_universe = StrListOption(
2✔
156
        default=default_interpreter_universe,
157
        help=softwrap(
158
            f"""
159
            All known Python major/minor interpreter versions that may be used by either
160
            your code or tools used by your code.
161

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

165
            This does not control which interpreter your code will use. Instead, to set your
166
            interpreter constraints, update `[python].interpreter_constraints`, the
167
            `interpreter_constraints` field, and relevant tool options like
168
            `[isort].interpreter_constraints` to tell Pants which interpreters your code
169
            actually uses. See {doc_url("docs/python/overview/interpreter-compatibility")}.
170

171
            All elements must be the minor and major Python version, e.g. `'2.7'` or `'3.10'`. Do
172
            not include the patch version.
173
            """
174
        ),
175
        advanced=True,
176
    )
177
    enable_resolves = BoolOption(
2✔
178
        default=False,
179
        help=softwrap(
180
            """
181
            Set to true to enable lockfiles for user code. See `[python].resolves` for an
182
            explanation of this feature.
183

184
            This option is mutually exclusive with `[python].requirement_constraints`. We strongly
185
            recommend using this option because it:
186

187
              1. Uses `--hash` to validate that all downloaded files are expected, which reduces\
188
                the risk of supply chain attacks.
189
              2. Enforces that all transitive dependencies are in the lockfile, whereas\
190
                constraints allow you to leave off dependencies. This ensures your build is more\
191
                stable and reduces the risk of supply chain attacks.
192
              3. Allows you to have multiple lockfiles in your repository.
193
            """
194
        ),
195
        advanced=True,
196
        mutually_exclusive_group="lockfile",
197
    )
198
    resolves = DictOption[str](
2✔
199
        default={"python-default": "3rdparty/python/default.lock"},
200
        help=softwrap(
201
            f"""
202
            A mapping of logical names to lockfile paths used in your project.
203

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

209
            If you only need a single resolve, run `{bin_name()} generate-lockfiles` to
210
            generate the lockfile.
211

212
            If you need multiple resolves:
213

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

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

233
            For example:
234

235
                python_sources(
236
                    resolve=parametrize("data-science", "web-app"),
237
                )
238

239
            You can name the lockfile paths what you would like; Pants does not expect a
240
            certain file extension or location.
241

242
            Only applies if `[python].enable_resolves` is true.
243
            """
244
        ),
245
        advanced=True,
246
    )
247
    default_resolve = StrOption(
2✔
248
        default="python-default",
249
        help=softwrap(
250
            """
251
            The default value used for the `resolve` field.
252

253
            The name must be defined as a resolve in `[python].resolves`.
254
            """
255
        ),
256
        advanced=True,
257
    )
258

259
    _default_to_resolve_interpreter_constraints = BoolOption(
2✔
260
        default=False,
261
        help=softwrap(
262
            """
263
            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.
264

265
            `[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.
266
            """
267
        ),
268
        advanced=True,
269
    )
270

271
    @memoized_property
2✔
272
    def default_to_resolve_interpreter_constraints(self) -> bool:
2✔
UNCOV
273
        if self._default_to_resolve_interpreter_constraints and not self.enable_resolves:
×
274
            raise OptionsError(
×
275
                softwrap(
276
                    """
277
                You cannot set `[python].default_to_resolve_interpreter_constraints = true` without setting `[python].enable_resolves = true`.
278

279
                Please either enable resolves or set `[python].default_to_resolve_interpreter_constraints = false` (the default setting).
280
                """
281
                )
282
            )
UNCOV
283
        return self._default_to_resolve_interpreter_constraints
×
284

285
    separate_lockfile_metadata_file = BoolOption(
2✔
286
        advanced=True,
287
        default=False,
288
        help=softwrap(
289
            """
290
            If set, lockfile metadata will be written to a separate sibling file, rather than
291
            prepended as a header to the lockfile (which has various disadvantages).
292
            This will soon become True by default and eventually the header option will be
293
            deprecated and then removed.
294
            """
295
        ),
296
    )
297
    default_run_goal_use_sandbox = BoolOption(
2✔
298
        default=True,
299
        help=softwrap(
300
            """
301
            The default value used for the `run_goal_use_sandbox` field of Python targets. See the
302
            relevant field for more details.
303
            """
304
        ),
305
    )
306
    pip_version = StrOption(
2✔
307
        default="24.2",
308
        help=softwrap(
309
            f"""
310
            Use this version of Pip for resolving requirements and generating lockfiles.
311

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

315
            N.B.: The `latest` value selects the latest of the choices listed by PEX which is not
316
            necessarily the latest Pip version released on PyPI.
317
            """
318
        ),
319
        advanced=True,
320
    )
321
    pex_builder = EnumOption(
2✔
322
        default=PexBuilder.pex,
323
        help=softwrap(
324
            """
325
            Which tool to use for installing dependencies when building PEX files.
326

327
            - `pex` (default): Use pip via PEX.
328
            - `uv` (experimental): Pre-install dependencies into a uv venv, then pass it
329
              to PEX via `--venv-repository`. When a PEX-native lockfile is available,
330
              uv installs the exact pinned versions with `--no-deps`.
331

332
            Only applies to non-internal, non-cross-platform PEX builds. Other builds
333
            silently fall back to pip.
334
            """
335
        ),
336
        advanced=True,
337
    )
338
    _resolves_to_interpreter_constraints = DictOption[list[str]](
2✔
339
        help=softwrap(
340
            """
341
            Override the interpreter constraints to use when generating a resolve's lockfile
342
            with the `generate-lockfiles` goal.
343

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

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

353
            Pants will validate that the interpreter constraints of your code using a
354
            resolve are compatible with that resolve's own constraints. For example, if your
355
            code is set to use `['==3.9.*']` via the `interpreter_constraints` field, but it's
356
            using a resolve whose interpreter constraints are set to `['==3.7.*']`, then
357
            Pants will error explaining the incompatibility.
358

359
            The keys must be defined as resolves in `[python].resolves`.
360
            """
361
        ),
362
        advanced=True,
363
    )
364
    _resolves_to_constraints_file = DictOption[str](
2✔
365
        help=softwrap(
366
            f"""
367
            When generating a resolve's lockfile, use a constraints file to pin the version of
368
            certain requirements. This is particularly useful to pin the versions of transitive
369
            dependencies of your direct requirements.
370

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

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

380
            You can use the key `{RESOLVE_OPTION_KEY__DEFAULT}` to set a default value for all
381
            resolves.
382
            """
383
        ),
384
        advanced=True,
385
    )
386
    _resolves_to_no_binary = DictOption[list[str]](
2✔
387
        help=softwrap(
388
            f"""
389
            When generating a resolve's lockfile, do not use binary packages (i.e. wheels) for
390
            these 3rdparty project names.
391

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

397
            You can use the key `{RESOLVE_OPTION_KEY__DEFAULT}` to set a default value for all
398
            resolves.
399

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

403
            Note that some packages are tricky to compile and may fail to install when this option
404
            is used on them. See https://pip.pypa.io/en/stable/cli/pip_install/#install-no-binary
405
            for details.
406
            """
407
        ),
408
        advanced=True,
409
    )
410
    _resolves_to_only_binary = DictOption[list[str]](
2✔
411
        help=softwrap(
412
            f"""
413
            When generating a resolve's lockfile, do not use source packages (i.e. sdists) for
414
            these 3rdparty project names, e.g `['django', 'requests']`.
415

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

421
            You can use the key `{RESOLVE_OPTION_KEY__DEFAULT}` to set a default value for all
422
            resolves.
423

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

427
            Packages without binary distributions will fail to install when this option is used on
428
            them. See https://pip.pypa.io/en/stable/cli/pip_install/#install-only-binary for
429
            details.
430
            """
431
        ),
432
        advanced=True,
433
    )
434
    _resolves_to_excludes = DictOption[list[str]](
2✔
435
        help=softwrap(
436
            """ Specifies requirements to exclude from a resolve and its
437
            lockfile.  Any distribution included in the PEX's resolve that
438
            matches the requirement is excluded from the built PEX along with
439
            all of its transitive dependencies that are not also required by
440
            other non-excluded distributions.  At runtime, the PEX will boot
441
            without checking the excluded dependencies are available.
442
            """
443
        ),
444
        advanced=True,
445
    )
446
    _resolves_to_overrides = DictOption[list[str]](
2✔
447
        help=softwrap(
448
            """ Specifies a transitive requirement to override in a resolve
449
            and its lockfile.  Overrides can either modify an existing
450
            dependency on a project name by changing extras, version
451
            constraints or markers or else they can completely swap out the
452
            dependency for a dependency on another project altogether. For the
453
            former, simply supply the requirement you wish. For example,
454
            specifying `--override cowsay==5.0` will override any transitive
455
            dependency on cowsay that has any combination of extras, version
456
            constraints or markers with the requirement `cowsay==5.0`. To
457
            completely replace cowsay with another library altogether, you can
458
            specify an override like `--override cowsay=my-cowsay>2`. This
459
            will replace any transitive dependency on cowsay that has any
460
            combination of extras, version constraints or markers with the
461
            requirement `my-cowsay>2`."""
462
        ),
463
        advanced=True,
464
    )
465

466
    _resolves_to_sources = DictOption[list[str]](
2✔
467
        help=softwrap(""" Defines a limited scope to use a named find links repo or
468
            index for specific dependencies in a resolve and its lockfile.
469
            Sources take the form `<name>=<scope>` where the name must match
470
            a find links repo or index defined via `[python-repos].indexes` or
471
            `[python-repos].find_links`. The scope can be a project name
472
            (e.g., `internal=torch` to resolve the `torch` project from the
473
            `internal` repo), a project name with a marker (e.g.,
474
            `internal=torch; sys_platform != 'darwin'` to resolve `torch` from
475
            the `internal` repo except on macOS), or just a marker (e.g.,
476
            `piwheels=platform_machine == 'armv7l'` to resolve from the
477
            `piwheels` repo when targeting 32bit ARM machines)."""),
478
        advanced=True,
479
    )
480

481
    _resolves_to_lock_style = DictOption[str](
2✔
482
        help=softwrap(
483
            f"""
484
            The style of lock to generate. Valid values are 'strict', 'sources', or 'universal'
485
            (additional styles may be supported in future PEX versions).
486

487
            The 'strict' style generates a lock file that contains exactly the
488
            distributions that would be used in a local PEX build. If an sdist would be used, the sdist is included, but if a
489
            wheel would be used, an accompanying sdist will not be included. The 'sources' style includes locks containing both
490
            wheels and the associated sdists when available. The 'universal' style generates a universal lock for all possible
491
            target interpreters and platforms, although the scope can be constrained via `[python].resolves_to_interpreter_constraints`. Of
492
            the three lock styles, only 'strict' can give you full confidence in the lock since it includes exactly the artifacts
493
            that are included in the local PEX you'll build to test the lock result with before checking in the lock. With the
494
            other two styles you lock un-vetted artifacts in addition to the 'strict' ones; so, even though you can be sure to
495
            reproducibly resolve those same un-vetted artifacts in the future, they're still un-vetted and could be innocently or
496
            maliciously different from the 'strict' artifacts you can locally vet before committing the lock to version control.
497
            The effects of the differences could range from failing a resolve using the lock when the un-vetted artifacts have
498
            different dependencies from their sibling artifacts, to your application crashing due to different code in the sibling
499
            artifacts to being compromised by differing code in the sibling artifacts. So, although the more permissive lock
500
            styles will allow the lock to work on a wider range of machines /are apparently more convenient, the convenience comes
501
            with a potential price and using these styles should be considered carefully.
502

503
            Expects a dictionary of resolve names from `[python].resolves` to style values.
504
            If a resolve is not set in the dictionary, it will default to 'universal'.
505

506
            Examples:
507
            - `{{'data-science': 'strict', 'web-app': 'universal'}}` - use strict style for data-science resolve, universal for web-app
508
            - `{{'python-default': 'sources'}}` - use sources style for the default resolve
509

510
            You can use the key `{RESOLVE_OPTION_KEY__DEFAULT}` to set a default value for all
511
            resolves.
512

513
            See https://docs.pex-tool.org/api/pex.html for more information on lockfile styles.
514
            """
515
        ),
516
        advanced=True,
517
    )
518

519
    _resolves_to_complete_platforms = DictOption[list[str]](
2✔
520
        help=softwrap(
521
            f"""
522
            The platforms the built PEX should be compatible with when generating lockfiles.
523

524
            Complete platforms allow you to create lockfiles for specific target platforms
525
            (e.g., different CPU architectures or operating systems) rather than the default
526
            universal platforms. This is particularly useful for cross-platform builds or
527
            when you need strict platform-specific dependencies.
528

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

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

536
            For example:
537
            `{{'python-default': ['3rdparty/platforms:linux_aarch64', '3rdparty/platforms:macos_arm64']}}`.
538

539
            You can use the key `{RESOLVE_OPTION_KEY__DEFAULT}` to set a default value for all
540
            resolves.
541

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

545
            See https://docs.pex-tool.org for more information.
546
            """
547
        ),
548
        advanced=True,
549
    )
550

551
    invalid_lockfile_behavior = EnumOption(
2✔
552
        default=InvalidLockfileBehavior.error,
553
        help=softwrap(
554
            """
555
            The behavior when a lockfile has requirements or interpreter constraints that are
556
            not compatible with what the current build is using.
557

558
            We recommend keeping the default of `error` for CI builds.
559

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

563
            Use `ignore` to avoid needing a lockfile header at all, e.g. if you are manually
564
            managing lockfiles rather than using the `generate-lockfiles` goal.
565
            """
566
        ),
567
        advanced=True,
568
    )
569
    resolves_generate_lockfiles = BoolOption(
2✔
570
        default=True,
571
        help=softwrap(
572
            """
573
            If False, Pants will not attempt to generate lockfiles for `[python].resolves` when
574
            running the `generate-lockfiles` goal.
575

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

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

586
            Warning: it will likely be slower to install manually generated user lockfiles than Pex
587
            ones because Pants cannot as efficiently extract the subset of requirements used for a
588
            particular task. See the option `[python].run_against_entire_lockfile`.
589
            """
590
        ),
591
        advanced=True,
592
    )
593
    run_against_entire_lockfile = BoolOption(
2✔
594
        default=False,
595
        help=softwrap(
596
            """
597
            If enabled, when running binaries, tests, and repls, Pants will use the entire
598
            lockfile file instead of just the relevant subset.
599

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

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

610
            This option does not affect packaging deployable artifacts, such as
611
            PEX files, wheels and cloud functions, which will still use just the exact
612
            subset of requirements needed.
613
            """
614
        ),
615
        advanced=True,
616
    )
617

618
    __constraints_deprecation_msg = softwrap(
2✔
619
        f"""
620
        We encourage instead migrating to `[python].enable_resolves` and `[python].resolves`,
621
        which is an improvement over this option. The `[python].resolves` feature ensures that
622
        your lockfiles are fully comprehensive, i.e. include all transitive dependencies;
623
        uses hashes for better supply chain security; and supports advanced features like VCS
624
        and local requirements, along with options `[python].resolves_to_only_binary`.
625

626
        To migrate, stop setting `[python].requirement_constraints` and
627
        `[python].resolve_all_constraints`, and instead set `[python].enable_resolves` to
628
        `true`. Then, run `{bin_name()} generate-lockfiles`.
629
        """
630
    )
631
    requirement_constraints = FileOption(
2✔
632
        default=None,
633
        help=softwrap(
634
            """
635
            When resolving third-party requirements for your own code (vs. tools you run),
636
            use this constraints file to determine which versions to use.
637

638
            Mutually exclusive with `[python].enable_resolves`, which we generally recommend as an
639
            improvement over constraints file.
640

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

645
            This only applies when resolving user requirements, rather than tools you run
646
            like Black and Pytest. To constrain tools, set `[tool].lockfile`, e.g.
647
            `[black].lockfile`.
648
            """
649
        ),
650
        advanced=True,
651
        mutually_exclusive_group="lockfile",
652
        removal_version="3.0.0.dev0",
653
        removal_hint=__constraints_deprecation_msg,
654
    )
655
    _resolve_all_constraints = BoolOption(
2✔
656
        default=True,
657
        help=softwrap(
658
            """
659
            (Only relevant when using `[python].requirement_constraints.`) If enabled, when
660
            resolving requirements, Pants will first resolve your entire
661
            constraints file as a single global resolve. Then, if the code uses a subset of
662
            your constraints file, Pants will extract the relevant requirements from that
663
            global resolve so that only what's actually needed gets used. If disabled, Pants
664
            will not use a global resolve and will resolve each subset of your requirements
665
            independently.
666

667
            Usually this option should be enabled because it can result in far fewer resolves.
668
            """
669
        ),
670
        advanced=True,
671
        removal_version="3.0.0.dev0",
672
        removal_hint=__constraints_deprecation_msg,
673
    )
674
    resolver_manylinux = StrOption(
2✔
675
        default="manylinux2014",
676
        help=softwrap(
677
            """
678
            Whether to allow resolution of manylinux wheels when resolving requirements for
679
            foreign linux platforms. The value should be a manylinux platform upper bound,
680
            e.g. `'manylinux2010'`, or else the string `'no'` to disallow.
681
            """
682
        ),
683
        advanced=True,
684
    )
685

686
    tailor_source_targets = BoolOption(
2✔
687
        default=True,
688
        help=softwrap(
689
            """
690
            If true, add `python_sources`, `python_tests`, and `python_test_utils` targets with
691
            the `tailor` goal."""
692
        ),
693
        advanced=True,
694
    )
695
    tailor_ignore_empty_init_files = BoolOption(
2✔
696
        "--tailor-ignore-empty-init-files",
697
        default=True,
698
        help=softwrap(
699
            """
700
            If true, don't add `python_sources` targets for `__init__.py` files that are both empty
701
            and where there are no other Python files in the directory.
702

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

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

709
            If you set to false, you may also want to set `[python-infer].init_files = "always"`.
710
            """
711
        ),
712
        advanced=True,
713
    )
714
    tailor_requirements_targets = BoolOption(
2✔
715
        default=True,
716
        help=softwrap(
717
            """
718
            If true, add `python_requirements`, `poetry_requirements`, and `pipenv_requirements`
719
            target generators with the `tailor` goal.
720

721
            `python_requirements` targets are added for any file that matches the pattern
722
            `*requirements*.txt`. You will need to manually add `python_requirements` for different
723
            file names like `reqs.txt`.
724

725
            `poetry_requirements` targets are added for `pyproject.toml` files with `[tool.poetry`
726
            in them.
727
            """
728
        ),
729
        advanced=True,
730
    )
731
    tailor_pex_binary_targets = BoolOption(
2✔
732
        default=False,
733
        help=softwrap(
734
            """
735
            If true, add `pex_binary` targets for Python files named `__main__.py` or with a
736
            `__main__` clause with the `tailor` goal.
737
            """
738
        ),
739
        advanced=True,
740
    )
741
    tailor_py_typed_targets = BoolOption(
2✔
742
        default=True,
743
        help=softwrap(
744
            """
745
            If true, add `resource` targets for marker files named `py.typed` with the `tailor` goal.
746
            """
747
        ),
748
        advanced=True,
749
    )
750
    tailor_test_file_globs = StrListOption(
2✔
751
        default=list(DEFAULT_TEST_FILE_GLOBS),
752
        help=softwrap(
753
            """
754
        Globs to match your test files. Used to decide which files should tailor
755
        python_tests() vs python_sources() targets.
756

757
        NB: This doesn't change the default set of files that a target owns, just the files
758
          that trigger tailoring of a target. If you need those to match (and you almost always do)
759
          then you should also create custom target type macros whose globs match these, and list
760
          them as substitutes for python_tests() and python_sources() in `[tailor].alias_mapping`.
761
          (see {doc_url("docs/writing-plugins/macros")} and
762
          {doc_url("reference/goals/tailor#alias_mapping")}).
763

764
        For example, you can set `[python].tailor_test_file_globs` to `["*_mytests.py"]`, and then
765
        create `my_pants_macros.py` with:
766

767
        ```
768
        def my_python_tests(**kwargs):
769
            if "sources" not in kwargs:
770
                kwargs["sources"] = ["*_mytests.py"]
771
            python_tests(**kwargs)
772

773

774
        def my_python_sources(**kwargs):
775
            if "sources" not in kwargs:
776
                kwargs["sources"] = ["*.py", "!*_mytests.py"]
777
            python_sources(**kwargs)
778
        ```
779

780
        And set the following in `pants.toml`:
781

782
        [global]
783
        build_file_prelude_globs = ["my_pants_macros.py"]
784

785
        [tailor]
786
        alias_mapping = { python_sources = "my_python_sources", python_tests = "my_python_tests" }
787
        """
788
        ),
789
        metavar="glob",
790
    )
791
    tailor_testutils_file_globs = StrListOption(
2✔
792
        default=list(DEFAULT_TESTUTIL_FILE_GLOBS),
793
        help=softwrap(
794
            """
795
        Globs to match your testutil files. Used to decide which files should tailor
796
        python_test_utils() vs python_sources() targets.
797

798
        See tailor_test_file_globs above for caveats and usage.
799
        """
800
        ),
801
        metavar="glob",
802
    )
803
    macos_big_sur_compatibility = BoolOption(
2✔
804
        default=False,
805
        help=softwrap(
806
            """
807
            If set, and if running on macOS Big Sur, use `macosx_10_16` as the platform
808
            when building wheels. Otherwise, the default of `macosx_11_0` will be used.
809
            This may be required for `pip` to be able to install the resulting distribution
810
            on Big Sur.
811
            """
812
        ),
813
        advanced=True,
814
    )
815
    enable_lockfile_targets = BoolOption(
2✔
816
        default=True,
817
        help=softwrap(
818
            """
819
            Create targets for all Python lockfiles defined in `[python].resolves`.
820

821
            The lockfile targets will then be used as dependencies to the `python_requirement`
822
            targets that use them, invalidating source targets per resolve when the lockfile
823
            changes.
824

825
            If another targets address is in conflict with the created lockfile target, it will
826
            shadow the lockfile target and it will not be available as a dependency for any
827
            `python_requirement` targets.
828
            """
829
        ),
830
        advanced=True,
831
    )
832
    repl_history = BoolOption(
2✔
833
        default=True,
834
        help="Whether to use the standard Python command history file when running a repl.",
835
    )
836

837
    @property
2✔
838
    def enable_synthetic_lockfiles(self) -> bool:
2✔
839
        return self.enable_resolves and self.enable_lockfile_targets
2✔
840

841
    @memoized_property
2✔
842
    def resolves_to_interpreter_constraints(self) -> dict[str, tuple[str, ...]]:
2✔
843
        result = {}
2✔
844
        unrecognized_resolves = []
2✔
845
        for resolve, ics in self._resolves_to_interpreter_constraints.items():
2✔
UNCOV
846
            if resolve not in self.resolves:
×
UNCOV
847
                unrecognized_resolves.append(resolve)
×
UNCOV
848
            if ics and self.warn_on_python2_usage:
×
849
                # Side-step import cycle.
UNCOV
850
                from pants.backend.python.util_rules.interpreter_constraints import (
×
851
                    warn_on_python2_usage_in_interpreter_constraints,
852
                )
853

UNCOV
854
                warn_on_python2_usage_in_interpreter_constraints(
×
855
                    ics,
856
                    description_of_origin=f"the `[python].resolves_to_interpreter_constraints` option for resolve {resolve}",
857
                )
858

UNCOV
859
            result[resolve] = tuple(ics)
×
860
        if unrecognized_resolves:
2✔
UNCOV
861
            raise UnrecognizedResolveNamesError(
×
862
                unrecognized_resolves,
863
                self.resolves.keys(),
864
                description_of_origin="the option `[python].resolves_to_interpreter_constraints`",
865
            )
866
        return result
2✔
867

868
    def _resolves_to_option_helper(
2✔
869
        self,
870
        option_value: dict[str, _T],
871
        option_name: str,
872
    ) -> dict[str, _T]:
873
        all_valid_resolves = set(self.resolves)
2✔
874
        unrecognized_resolves = set(option_value.keys()) - {
2✔
875
            RESOLVE_OPTION_KEY__DEFAULT,
876
            *all_valid_resolves,
877
        }
878
        if unrecognized_resolves:
2✔
UNCOV
879
            raise UnrecognizedResolveNamesError(
×
880
                sorted(unrecognized_resolves),
881
                {*all_valid_resolves, RESOLVE_OPTION_KEY__DEFAULT},
882
                description_of_origin=f"the option `[python].{option_name}`",
883
            )
884
        default_val = option_value.get(RESOLVE_OPTION_KEY__DEFAULT)
2✔
885
        if not default_val:
2✔
886
            return option_value
2✔
UNCOV
887
        return {resolve: option_value.get(resolve, default_val) for resolve in all_valid_resolves}
×
888

889
    @memoized_method
2✔
890
    def resolves_to_constraints_file(self) -> dict[str, str]:
2✔
891
        return self._resolves_to_option_helper(
2✔
892
            self._resolves_to_constraints_file,
893
            "resolves_to_constraints_file",
894
        )
895

896
    @memoized_method
2✔
897
    def resolves_to_no_binary(self) -> dict[str, list[str]]:
2✔
898
        return {
2✔
899
            resolve: [canonicalize_name(v) for v in vals]
900
            for resolve, vals in self._resolves_to_option_helper(
901
                self._resolves_to_no_binary,
902
                "resolves_to_no_binary",
903
            ).items()
904
        }
905

906
    @memoized_method
2✔
907
    def resolves_to_only_binary(self) -> dict[str, list[str]]:
2✔
908
        return {
2✔
909
            resolve: sorted([canonicalize_name(v) for v in vals])
910
            for resolve, vals in self._resolves_to_option_helper(
911
                self._resolves_to_only_binary,
912
                "resolves_to_only_binary",
913
            ).items()
914
        }
915

916
    @memoized_method
2✔
917
    def resolves_to_excludes(self) -> dict[str, list[str]]:
2✔
918
        return {
2✔
919
            resolve: sorted(vals)
920
            for resolve, vals in self._resolves_to_option_helper(
921
                self._resolves_to_excludes,
922
                "resolves_to_excludes",
923
            ).items()
924
        }
925

926
    @memoized_method
2✔
927
    def resolves_to_overrides(self) -> dict[str, list[str]]:
2✔
928
        return {
2✔
929
            resolve: sorted(vals)
930
            for resolve, vals in self._resolves_to_option_helper(
931
                self._resolves_to_overrides,
932
                "resolves_to_overrides",
933
            ).items()
934
        }
935

936
    @memoized_method
2✔
937
    def resolves_to_sources(self) -> dict[str, list[str]]:
2✔
938
        return {
2✔
939
            resolve: sorted(vals)
940
            for resolve, vals in self._resolves_to_option_helper(
941
                self._resolves_to_sources,
942
                "resolves_to_sources",
943
            ).items()
944
        }
945

946
    @memoized_method
2✔
947
    def resolves_to_lock_style(self) -> dict[str, str]:
2✔
948
        return self._resolves_to_option_helper(
2✔
949
            self._resolves_to_lock_style,
950
            "resolves_to_lock_style",
951
        )
952

953
    @memoized_method
2✔
954
    def resolves_to_complete_platforms(self) -> dict[str, list[str]]:
2✔
955
        return self._resolves_to_option_helper(
2✔
956
            self._resolves_to_complete_platforms,
957
            "resolves_to_complete_platforms",
958
        )
959

960
    @property
2✔
961
    def manylinux(self) -> str | None:
2✔
962
        manylinux = cast(str | None, self.resolver_manylinux)
2✔
963
        if manylinux is None or manylinux.lower() in ("false", "no", "none"):
2✔
964
            return None
×
965
        return manylinux
2✔
966

967
    @property
2✔
968
    def resolve_all_constraints(self) -> bool:
2✔
969
        if (
2✔
970
            self._resolve_all_constraints
971
            and not self.options.is_default("resolve_all_constraints")
972
            and not self.requirement_constraints
973
        ):
UNCOV
974
            raise ValueError(
×
975
                softwrap(
976
                    """
977
                    `[python].resolve_all_constraints` is enabled, so
978
                    `[python].requirement_constraints` must also be set.
979
                    """
980
                )
981
            )
982
        return self._resolve_all_constraints
2✔
983

984
    @property
2✔
985
    def scratch_dir(self):
2✔
986
        return os.path.join(self.options.pants_workdir, *self.options_scope.split("."))
×
987

988
    def compatibility_or_constraints(
2✔
989
        self, compatibility: Iterable[str] | None, resolve: str | None
990
    ) -> tuple[str, ...]:
991
        """Return either the given `compatibility` field or the global interpreter constraints.
992

993
        If interpreter constraints are supplied by the CLI flag, return those only.
994
        """
995
        if self.options.is_flagged("interpreter_constraints"):
2✔
996
            return self.interpreter_constraints
2✔
997
        if compatibility:
2✔
998
            return tuple(compatibility)
2✔
999
        if resolve and self.default_to_resolve_interpreter_constraints:
2✔
UNCOV
1000
            return self.resolves_to_interpreter_constraints.get(
×
1001
                resolve, self.interpreter_constraints
1002
            )
1003
        return self.interpreter_constraints
2✔
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