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:
ParamTypeComma-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 configurableseparator(defaults to,), parses it into atuple[str, ...]and validates each value againstchoiceswhen that set is non-empty.The rendered metavar is
[a,b,c](separator-joined, parallel toChoice’s[a|b|c]):click_extra.highlight._HelpColorsMixinauto-detects the separator and highlights each individual value the same way it does forChoice.Note
Click ships no single-token equivalent: its idiom is
click.Choicewithmultiple=True, which repeats the flag (--tag a --tag b). pallets/click#2771 asks for a separator-based variant.MultiChoicefollows the SQLSELECT a, b, cconvention of the tabular use cases Click Extra supports, withclick_extra.table_options.ColumnsOptionas the headline consumer.Initialize the type.
- Parameters:
choices (
Sequence[str]) – the accepted values. When non-empty,convert()rejects unknown tokens withfail. 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) – whenTrue, a token must match one ofchoicesexactly. By default tokens match case-insensitively, as withEnumChoiceandThemeChoice, and the returned tuple holds the canonical (original-case) values fromchoices.
- get_metavar(param, ctx)[source]¶
Render
[a<sep>b<sep>c]whenchoicesis set,Noneotherwise.Nonefalls back to Click’s default rendering (the uppercasedname, likeMULTI).
- convert(value, param, ctx)[source]¶
Split
valueonseparatorand 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.
- class click_extra.types.LazyChoice(load, case_sensitive=True)[source]¶
Bases:
ChoiceA
Choicewhose values are produced on first use rather than at decoration.click.Choicefreezes 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. EveryChoicemethod readschoices, so the help screen, the generated documents and shell completion see the loaded values like any other.Keep the
loadcallable, which is called on each read ofchoices.- Parameters:
load (
Callable[[],Iterable[str]]) – returns the accepted values. Called on each access ofchoices, so a cheap loader, or a cached one, is expected.case_sensitive (
bool) – as forclick.Choice.
- class click_extra.types.ChoiceSource(*values)[source]¶
Bases:
EnumSource 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:
ChoiceChoice type for
Enum.Allows to select which part of the members to use as choice strings, by setting the
choice_sourceparameter to one of:ChoiceSource.KEYorChoiceSource.NAMEto use the key (thenameproperty),ChoiceSource.VALUEto use thevalue,ChoiceSource.STRto use thestr()string representation, orA custom callable that takes an
Enummember and returns a string.
Defaults to
ChoiceSource.STR, which only requires you to define the__str__()method on yourEnumto produce beautiful choice strings.The
transformparameter 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 whileshow_aliasesis on: aliases are reachable throughChoiceSource.KEY,ChoiceSource.NAMEandChoiceSource.VALUEalone, which are stuck on raw Python identifiers.Same as
click.Choice, but takes anEnumaschoices.Also defaults to case-insensitive matching.
- Raises:
TypeError – if
choicesis not anEnumsubclass.ValueError – if
choice_sourceis a string naming noChoiceSourcemember.
- choices: tuple[str, ...]¶
The strings available as choice.
Hint
Contrary to the parent
Choiceclass, we store choices directly as strings, not theEnummembers 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’smember.The string produced by the choice source is passed through
transform.- Return type:
- 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
Durationparameter type: it accepts the same three input shapes but returnsNoneinstead of raising whenvaluematches none of them, so it suits classifying values read from files or other machine sources. UnlikeDuration, it does not collapse a zero duration toNone:parse_duration("0")istimedelta(0), letting callers tell a zero duration from an unparsable value.Noneis returned only for an empty value, a future timestamp, or a value matching no known form.- Parameters:
- Return type:
- Returns:
The parsed
timedelta(possibly zero), orNone.
- 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"istimedelta(0)), orNonefor anything that is not a friendly duration: ISO 8601 forms, calendar units (months, years), and empty or unrecognized values. Seeparse_duration()for the format-detecting umbrella.
- 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"istimedelta(0)), orNonefor anything that is not an ISO 8601 duration: friendly forms, calendar (year or month) components, and empty or unrecognized values. Seeparse_duration()for the format-detecting umbrella.
- class click_extra.types.Duration[source]¶
Bases:
ParamTypeParse 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 like7. Case-insensitive.ISO 8601 duration:
P7D,PT12H,P1WT6H. Case-insensitive.RFC 3339 absolute timestamp:
2024-05-01T00:00:00Zor with an offset like+02:00. Converted at parse time to its age,now - timestamp.
Some inputs parse to
Noneinstead of atimedelta: a zero duration, an empty string, and a timestamp in the future. Cutoff options (cooldowns, timeouts, retention windows, cache TTLs) readNoneas “no cutoff”, so a0on 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 returnsNoneinstead 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
daysorweeksinstead.