click_extra.jobs module¶

        classDiagram
  ExtraOption <|-- JobsOption
  ParamType <|-- JobCount
    

The --jobs option, and the fan-out primitives that honor its count.

JobsOption resolves the count, its auto and max keywords included, and publishes it on ctx.meta. run_jobs() and run_lanes() spread work over a thread pool of that size, and resolve_jobs() holds the policy both apply.

Todo

Stop turning a RuntimeError of the wait in _wait_result() back into the KeyboardInterrupt it replaced, once python/cpython#118433 is fixed in every free-threaded Python Click Extra supports.

click_extra.jobs.CPU_COUNT = 4¶

Number of logical CPUs available to this process, or None if undetermined.

A count of logical processors (hardware threads), resolved by _logical_cpu_count(): os.process_cpu_count() on Python 3.13+, falling back to os.cpu_count() on older runtimes. On a CPU with simultaneous multi-threading (Intel Hyper-Threading, AMD SMT) a 4-physical-core chip reports 8. It is therefore not a count of physical cores, and is usually larger than what physical-core tools report, such as psutil.cpu_count(logical=False) or pytest-xdist’s -n auto (which counts physical cores). Parallelism here is keyed on the logical count on purpose: subprocess- and I/O-bound work overlaps well across hardware threads.

click_extra.jobs.DEFAULT_JOBS = 3¶

Default number of parallel jobs: CPU_COUNT minus one reserved core.

Leaves one logical CPU free for the main process and system tasks, but only on hosts with three logical CPUs or more: on smaller hosts the reservation would collapse the pool to a single (sequential) worker, and threads waiting on subprocesses and I/O cost nothing there, so the whole machine is used instead. Falls back to 1 (sequential) when the count cannot be determined.

Caution

On a single-CPU host this still resolves to 1 and the default silently runs sequentially. JobCount.convert() logs whenever a parallel-intent keyword collapses to a single job this way: as a warning for an explicit request, at info level for the option’s own default.

class click_extra.jobs.JobCount[source]¶

Bases: ParamType

Parse a --jobs value: an integer or the auto/max keyword.

Resolves the symbolic keywords against the host’s logical CPU count (CPU_COUNT), counting hardware threads, not physical cores:

  • auto resolves to DEFAULT_JOBS (one fewer than the available logical CPUs, except on hosts with fewer than three, where reserving a core would leave a single worker), the same heuristic used as the option’s default.

  • max resolves to CPU_COUNT (every available logical CPU).

Any other token is parsed as an integer and left to JobsOption.validate_jobs() for clamping and range-checking. Resolving the keywords here keeps the value handed downstream a plain int, so consumers never have to know about the keywords.

name: str = 'jobs'¶

the descriptive name of this type

choices = ('auto', 'max')¶

Symbolic keywords accepted besides an integer count, in render order.

Exposed as choices so the help colorizer highlights them like click.Choice values: the keyword collector duck-types on this attribute (see the getattr(param.type, "choices", ...) branch in _HelpColorsMixin._collect_params). It is also the single source of truth reused by get_metavar() and convert(), so the metavar and the parser never drift apart.

get_metavar(param, ctx)[source]¶

Render [auto|max|INTEGER] (brackets included, as Choice does).

Return type:

str

convert(value, param, ctx)[source]¶

Resolve a keyword to a logical-core count, else parse as an integer.

An already-resolved integer is returned untouched, so option defaults and re-validation can flow back through conversion unharmed. When a parallel-intent keyword (auto/max) resolves to a single job, the collapse is logged: the request reads as “use several cores”, but the host has too few logical CPUs, so execution is silently sequential. An explicit request (command line, environment variable, config file) logs a warning; the option’s own default only logs at info level, else every bare invocation on a 1-CPU host would emit a warning the user never asked for, polluting captured runner streams and the CLI output rendered in Sphinx docs.

Return type:

int

shell_complete(ctx, param, incomplete)[source]¶

Suggest the auto/max keywords; an integer count is free-form.

Completion proposes only the symbolic keywords, matched case-insensitively to mirror how convert() lower-cases its input. An integer has no finite set to enumerate, so none is offered, yet convert() still accepts one.

Return type:

list[CompletionItem]

class click_extra.jobs.JobsOption(param_decls=None, *, default='auto', expose_value=False, show_default=True, type=<click_extra.jobs.JobCount object>, help="Number of parallel jobs. Accepts an integer, auto (the host's logical CPUs, minus one when there are three or more) or max (all logical CPUs). --jobs 0 runs sequentially.", **kwargs)[source]¶

Bases: ExtraOption

A pre-configured --jobs option to control parallel execution.

Accepts an integer or one of two keywords resolved by JobCount: auto (the default: one fewer than the available logical CPU cores, leaving a core free for the main process and system tasks, except on hosts with fewer than three logical CPUs, where reserving one would leave a single worker) and max (every available logical CPU core). A value of 0 disables parallelism and runs sequentially.

The core count is the number of logical CPUs (hardware threads) available to the process, not physical cores: see CPU_COUNT. On a host with a single logical CPU, auto/max resolve to a single job and JobCount logs that execution will be sequential: as a warning when the keyword was requested explicitly, at info level when it came from the option’s own default.

The resolved value is stored as an int in ctx.meta[click_extra.context.JOBS].

Warning

JobsOption only resolves and publishes the job count: it does not drive any concurrency by itself. Pass it to run_jobs() (which reads the resolved ctx.meta[click_extra.context.JOBS] count), or read that value yourself and act on it.

validate_jobs(ctx, param, value)[source]¶

Validate the resolved job count and store it in context metadata.

JobCount has already resolved any auto/max keyword to an integer by the time this runs. A value of 0 disables parallelism: it is rounded up to 1 (sequential execution) with a warning. Negative values are likewise clamped to 1. A count above the available cores is honored: the pool is a ThreadPoolExecutor, and oversubscription is how I/O- and subprocess-bound work overlaps, so the warning only flags the CPU-bound case where extra threads just contend for the GIL. The resolved count is then logged at info level next to the host’s logical CPU count (CPU_COUNT), so a CLI’s parallelism is visible under --verbosity INFO.

Return type:

None

click_extra.jobs.resolve_jobs(ctx, count, *, serial_at_debug=False)[source]¶

Resolve how many worker threads to use for a batch of count items.

Returns the number of items to process in parallel; 1 means run sequentially in the calling thread. This is the policy shared by run_jobs() and run_lanes(), exposed on its own for callers that must know the resolved count before they fan out (for example to pick a progress-rendering mode). It collapses to sequential when:

  • there is no active CLI context (programmatic or test use),

  • a single item leaves nothing to parallelize, or

  • the resolved JobsOption count (ctx.meta[click_extra.context.JOBS]) is 1 or less.

Otherwise that count wins, capped at count: there is no point spinning up more workers than there are items.

Parameters:
  • ctx (Context | None) – the active Click context, read for the resolved --jobs count (and, with serial_at_debug, the verbosity). None forces sequential.

  • count (int) – how many items are about to be scheduled.

  • serial_at_debug (bool) – when set, also collapse to sequential at DEBUG verbosity, where coherent per-worker log narration matters more than the speed-up (interleaved threads would scramble it). Off by default.

Return type:

int

click_extra.jobs.run_jobs(func, items, *, jobs=None, serial_at_debug=False)[source]¶

Run func over items, parallelized per the resolved --jobs count.

The worker count is taken from jobs when given, else resolved from the active command’s JobsOption value by resolve_jobs(), else 1. With a single worker (or at most one item) the items run sequentially and lazily, so a caller can stop early on the first result (for example to abort on the first failure); otherwise they run in a thread pool. Either way results are yielded in submission order, like map().

This is the single-task-per-item special case of run_lanes(), which runs every item as a lane of its own. Reach for run_lanes() when some items must run serially relative to one another while others run concurrently.

The pool is thread-based, which suits the I/O- and subprocess-bound work CLI tools usually parallelize (each child releases the GIL). The count is a number of logical CPUs: see CPU_COUNT.

items is never materialized: only a bounded window of tasks is queued at a time, so an unbounded or expensive-to-produce stream stays memory-flat and is read no further than the caller consumes.

Parameters:
  • func (Callable[[T], R]) – Called once per item; its return value is yielded.

  • items (Iterable[T]) – The work items. Read lazily, a window at a time.

  • jobs (int | None) – Override the worker count instead of reading it from the context. 1 or fewer forces sequential execution.

  • serial_at_debug (bool) – forwarded to resolve_jobs() when jobs is not given: collapse to sequential at DEBUG verbosity.

Return type:

Generator[R, None, None]

Returns:

An iterator over func’s results, in the order of items.

click_extra.jobs.run_lanes(func, lanes, *, jobs=None, serial_at_debug=False)[source]¶

Run func over grouped items: serial within a lane, concurrent across.

Each lane is an iterable of items. func is mapped over every item, but a lane’s own items run serially and in order on a single worker, while distinct lanes run concurrently up to the resolved --jobs count. This is the right primitive when some work must be serialized relative to itself (a shared lock, a rate limit, one mailbox file, one package-manager backend) yet still overlap with unrelated work.

run_jobs() is the degenerate case where every lane holds a single item. Concurrency is sized by the number of lanes (one worker per lane), since a lane never splits across workers. A single lane runs in the calling thread, whatever the worker count.

Results are yielded in lane-submission order, a lane’s items in order, like map(). The run stays lazy at any worker count: a lane is materialized only when it is about to be scheduled, and only a bounded window of lanes is in flight, so a caller can break early and the lanes behind it are never read. A lane runs entirely on one worker, so a stateful resource bound to the lane (a per-lane cache, a connection) is touched by only that one thread and needs no lock.

Parameters:
  • func (Callable[[T], R]) – Called once per item; its return value is yielded.

  • lanes (Iterable[Iterable[T]]) – The lanes, each an iterable of items. Read lazily, a window of lanes at a time; a lane’s own items are materialized when it is scheduled.

  • jobs (int | None) – Override the worker count instead of reading it from the context. 1 or fewer forces fully sequential execution.

  • serial_at_debug (bool) – forwarded to resolve_jobs() when jobs is not given: collapse to sequential at DEBUG verbosity.

Return type:

Generator[R, None, None]

Returns:

An iterator over func’s results, lane by lane in submission order.