click_extra.types module¶

        classDiagram
  Choice <|-- EnumChoice
  Choice <|-- LazyChoice
  Enum <|-- ChoiceSource
  ParamType <|-- Duration
  ParamType <|-- MultiChoice
    

Custom click.ParamType subclasses for multi-pick, Enum choices and durations, plus the standalone duration parsers that back Duration.

class click_extra.types.MultiChoice(choices=(), separator=',', case_sensitive=False)[source]¶

Bases: ParamType

Comma-separated multi-pick from a fixed set of values.

The pick-many counterpart to click.Choice. Accepts a single token containing several values joined by a configurable separator (defaults to ,), parses it into a tuple[str, ...] and validates each value against choices when that set is non-empty.

The rendered metavar is [a,b,c] (separator-joined, parallel to Choice’s [a|b|c]): click_extra.highlight._HelpColorsMixin auto-detects the separator and highlights each individual value the same way it does for Choice.

Note

Click ships no single-token equivalent: its idiom is click.Choice with multiple=True, which repeats the flag (--tag a --tag b). pallets/click#2771 asks for a separator-based variant. MultiChoice follows the SQL SELECT a, b, c convention of the tabular use cases Click Extra supports, with click_extra.table_options.ColumnsOption as the headline consumer.

Initialize the type.

Parameters:
  • choices (Sequence[str]) – the accepted values. When non-empty, convert() rejects unknown tokens with fail. When empty, the type behaves as a pure separator-aware parser and leaves validation to the consumer.

  • separator (str) – the token boundary. Use any single character; this also drives the metavar rendering ([a<sep>b<sep>c]).

  • case_sensitive (bool) – when True, a token must match one of choices exactly. By default tokens match case-insensitively, as with EnumChoice and ThemeChoice, and the returned tuple holds the canonical (original-case) values from choices.

name: str = 'multi'¶

the descriptive name of this type

get_metavar(param, ctx)[source]¶

Render [a<sep>b<sep>c] when choices is set, None otherwise.

None falls back to Click’s default rendering (the uppercased name, like MULTI).

Return type:

str | None

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

Split value on separator and validate each token.

An already-parsed tuple or list keeps its elements verbatim rather than being split again, then goes through the same validation as a raw token: it reaches here from a configuration file as readily as from a default the CLI author declared, and only that check tells a valid selection from a typo. Empty tokens (consecutive separators, trailing separator) are dropped silently.

Return type:

tuple[str, ...]

class click_extra.types.LazyChoice(load, case_sensitive=True)[source]¶

Bases: Choice

A Choice whose values are produced on first use rather than at decoration.

click.Choice freezes its values when the option is declared, which is at import time for a module-level command. Taking a loader instead keeps the module providing the values off the startup path of the CLI: the values are only needed to parse, complete or document the option, never to import it. Every Choice method reads choices, so the help screen, the generated documents and shell completion see the loaded values like any other.

Keep the load callable, which is called on each read of choices.

Parameters:
  • load (Callable[[], Iterable[str]]) – returns the accepted values. Called on each access of choices, so a cheap loader, or a cached one, is expected.

  • case_sensitive (bool) – as for click.Choice.

property choices: tuple[str, ...]¶

The values, read from the loader on each access.

Setter accepts:

Iterable[str]

class click_extra.types.ChoiceSource(*values)[source]¶

Bases: Enum

Source of choices for EnumChoice.

KEY = 'key'¶
NAME = 'name'¶
VALUE = 'value'¶
STR = 'str'¶
class click_extra.types.EnumChoice(choices, case_sensitive=False, choice_source=ChoiceSource.STR, show_aliases=False, transform=None)[source]¶

Bases: Choice

Choice type for Enum.

Allows to select which part of the members to use as choice strings, by setting the choice_source parameter to one of:

  • ChoiceSource.KEY or ChoiceSource.NAME to use the key (the name property),

  • ChoiceSource.VALUE to use the value,

  • ChoiceSource.STR to use the str() string representation, or

  • A custom callable that takes an Enum member and returns a string.

Defaults to ChoiceSource.STR, which only requires you to define the __str__() method on your Enum to produce beautiful choice strings.

The transform parameter takes a callable reshaping the string produced by the source. It composes with every source, and is the only way to spell choices in a CLI-friendly case while show_aliases is on: aliases are reachable through ChoiceSource.KEY, ChoiceSource.NAME and ChoiceSource.VALUE alone, which are stuck on raw Python identifiers.

Same as click.Choice, but takes an Enum as choices.

Also defaults to case-insensitive matching.

Raises:
choices: tuple[str, ...]¶

The strings available as choice.

Hint

Contrary to the parent Choice class, we store choices directly as strings, not the Enum members themselves. That way there is no surprises when displaying them to the user.

This trick bypass Enum-specific code path in the Click library. Because, after all, a terminal environment only deals with strings: arguments, parameters, parsing, help messages, environment variables, etc.

get_choice_string(member)[source]¶

Derive the choice string from the given Enum’s member.

The string produced by the choice source is passed through transform.

Return type:

str

normalize_choice(choice, ctx)[source]¶

Expand the parent’s normalize_choice() to accept Enum members as input.

An Enum member is mapped to its choice string first; any other value is passed to the parent untouched.

Return type:

str

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

Convert the input value to the corresponding Enum member.

The parent’s convert() is going to return the choice string, which we then map back to the corresponding Enum member.

Return type:

Enum

click_extra.types.parse_duration(value, *, now=None)[source]¶

Parse a friendly, ISO 8601 or RFC 3339 duration into a timedelta.

The soft, library-friendly counterpart of the Duration parameter type: it accepts the same three input shapes but returns None instead of raising when value matches none of them, so it suits classifying values read from files or other machine sources. Unlike Duration, it does not collapse a zero duration to None: parse_duration("0") is timedelta(0), letting callers tell a zero duration from an unparsable value. None is returned only for an empty value, a future timestamp, or a value matching no known form.

Parameters:
  • value (Any) – The duration to parse. An existing timedelta (or None) is returned unchanged.

  • now (datetime | None) – Reference instant for an RFC 3339 timestamp’s age; defaults to the current UTC time.

Return type:

timedelta | None

Returns:

The parsed timedelta (possibly zero), or None.

click_extra.types.parse_friendly_duration(value)[source]¶

Parse only a friendly duration (7 days, 12h, a bare number of days).

Returns the parsed timedelta (possibly zero, so "0 days" is timedelta(0)), or None for anything that is not a friendly duration: ISO 8601 forms, calendar units (months, years), and empty or unrecognized values. See parse_duration() for the format-detecting umbrella.

Return type:

timedelta | None

click_extra.types.parse_iso8601_duration(value)[source]¶

Parse only an ISO 8601 duration (P7D, PT12H, P1WT6H).

Returns the parsed timedelta (possibly zero, so "PT0S" is timedelta(0)), or None for anything that is not an ISO 8601 duration: friendly forms, calendar (year or month) components, and empty or unrecognized values. See parse_duration() for the format-detecting umbrella.

Return type:

timedelta | None

class click_extra.types.Duration[source]¶

Bases: ParamType

Parse a duration or an age into a datetime.timedelta.

Accepts three input shapes:

  • Friendly duration: 7 days, 1 week, 12h, 30m, 45s, or a bare number of days like 7. Case-insensitive.

  • ISO 8601 duration: P7D, PT12H, P1WT6H. Case-insensitive.

  • RFC 3339 absolute timestamp: 2024-05-01T00:00:00Z or with an offset like +02:00. Converted at parse time to its age, now - timestamp.

Some inputs parse to None instead of a timedelta: a zero duration, an empty string, and a timestamp in the future. Cutoff options (cooldowns, timeouts, retention windows, cache TTLs) read None as “no cutoff”, so a 0 on the command line disables the gate and overrides a value set in a configuration file.

To parse outside a Click parameter (classifying a value read from a file, say), reach for the soft parse_duration() family, which returns None instead of raising on an unrecognized value.

Note

Durations resolve to a fixed number of seconds, assuming a day is 24 hours. The local time zone, DST transitions, and calendar boundaries are ignored. Calendar units (months, years) are rejected for the same reason: 28-31 days and 365-366 days make them unsuitable for a precise cutoff. Use days or weeks instead.

name: str = 'duration'¶

the descriptive name of this type

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

Coerce value to a datetime.timedelta (or None).

Delegates to _parse_duration_strict(), turning its ValueError into a Click parameter error via fail(). A parsed zero duration collapses to None, so 0 disables a cutoff option.

Return type:

timedelta | None