parameter-types.md
This file
Path
docs/parameter-types.md
257 lines · 9.2 KiB · Markdown
Last changed by
Stable (#3851)Rowlando13before adoption6aabf09
History of this fileTake it
Move Parameter-types doc from reST to MyST (#3041)Rowlando13before adoption23780fa
lines 1–72why, one step back1(parameter-types)=23# Parameter Types45```{currentmodule} click6```78When the parameter type is set using `type`, Click will leverage the type to make your life easier, for example adding9data to your help pages. Most examples are done with options, but types are available to options and arguments.1011```{contents}12---13depth: 214local: true15---16```1718## Built-in Types Examples1920(choice-opts)=2122### Choice2324Sometimes, you want to have a parameter be a choice of a list of values. In that case you can use {class}`Choice` type.25It can be instantiated with a list of valid values. The originally passed choice will be returned, not the str passed on26the command line. Token normalization functions and `case_sensitive=False` can cause the two to be different but still27match. {meth}`Choice.normalize_choice` for more info.282930Example:3132```{eval-rst}33.. click:example::3435 import enum3637 class HashType(enum.Enum):38 MD5 = enum.auto()39 SHA1 = enum.auto()4041 @click.command()42 @click.option('--hash-type',43 type=click.Choice(HashType, case_sensitive=False))44 def digest(hash_type: HashType):45 click.echo(hash_type)4647What it looks like:4849.. click:run::5051 invoke(digest, args=['--hash-type=MD5'])52 println()53 invoke(digest, args=['--hash-type=md5'])54 println()55 invoke(digest, args=['--hash-type=foo'])56 println()57 invoke(digest, args=['--help'])58```5960Any iterable may be passed to {class}`Choice`. If an `Enum` is passed, the names of the enum members will be used as61valid choices.6263Choices work with options that have `multiple=True`. If a `default` value is given with `multiple=True`, it should be a64list or tuple of valid choices.6566Choices should be unique after normalization, see {meth}`Choice.normalize_choice` for more info.6768```{versionchanged} 7.169The resulting value from an option will always be one of the originally passed choices70regardless of `case_sensitive`.71```72`ParamType` and other typing improvements (#3371)Rowlando13before adoption8a2b489
lines 73–78why, one step back73```{versionchanged} 8.4.074{class}`Choice` is now generic. Parameterize it with the choice value type75({class}`!Choice[HashType]` for an enum, {class}`!Choice[str]` for plain76strings) to enable type-checked consumers.77```78Move Parameter-types doc from reST to MyST (#3041)Rowlando13before adoption23780fa
lines 79–155why, one step back79(ranges)=8081### Int and Float Ranges8283The {class}`IntRange` type extends the {data}`INT` type to ensure the value is contained in the given range. The84{class}`FloatRange` type does the same for {data}`FLOAT`.8586If `min` or `max` is omitted, that side is *unbounded*. Any value in that direction is accepted. By default, both bounds87are *closed*, which means the boundary value is included in the accepted range. `min_open` and `max_open` can be used to88exclude that boundary from the range.8990If `clamp` mode is enabled, a value that is outside the range is set to the boundary instead of failing. For example,91the range `0, 5` would return `5` for the value `10`, or `0` for the value `-1`. When using {class}`FloatRange`, `clamp`92can only be enabled if both bounds are *closed* (the default).9394```{eval-rst}95.. click:example::9697 @click.command()98 @click.option("--count", type=click.IntRange(0, 20, clamp=True))99 @click.option("--digit", type=click.IntRange(0, 9))100 def repeat(count, digit):101 click.echo(str(digit) * count)102103.. click:run::104105 invoke(repeat, args=['--count=100', '--digit=5'])106 invoke(repeat, args=['--count=6', '--digit=12'])107```108109## Built-in Types Listing110111The supported parameter {ref}`click-api-types` are112113- `str` / {data}`click.STRING`: The default parameter type which indicates unicode strings.114115- `int` / {data}`click.INT`: A parameter that only accepts integers.116117- `float` / {data}`click.FLOAT`: A parameter that only accepts floating point values.118119- `bool` / {data}`click.BOOL`: A parameter that accepts boolean values. This is automatically used for boolean flags.120 The string values "1", "true", "t", "yes", "y", and "on" convert to `True`. "0", "false", "f", "no", "n", and "off"121 convert to `False`.122123- {data}`click.UUID`: A parameter that accepts UUID values. This is not automatically guessed but represented as124 {class}`uuid.UUID`.125126```{eval-rst}127* .. autoclass:: Choice128 :noindex:129```130131```{eval-rst}132* .. autoclass:: DateTime133 :noindex:134```135136```{eval-rst}137* .. autoclass:: File138 :noindex:139```140141```{eval-rst}142* .. autoclass:: FloatRange143 :noindex:144```145146```{eval-rst}147* .. autoclass:: IntRange148 :noindex:149```150151```{eval-rst}152* .. autoclass:: Path153 :noindex:154```155Stable (#3851)Rowlando13before adoption6aabf09
lines 156–207why, one step back156(type-inference)=157158## How Click Infers a Type159160When `type` is not given, Click infers it from `default`. Only the defaults listed below161are recognized. Every other default gives {data}`STRING`.162163| `default` | Inferred type |164| ------------------------------------------------ | ----------------------------------------------- |165| not given, or `None` | {data}`STRING` |166| `"git"` | {data}`STRING` |167| `5` | {data}`INT` |168| `1.5` | {data}`FLOAT` |169| `True` | {data}`BOOL` |170| `[]` or `()` | {data}`STRING` |171| `[1, 2]` or `(1, 2)` | {data}`INT` |172| `[1.5, 2.5]` | {data}`FLOAT` |173| `[1, "git"]` | {data}`INT` |174| `[(1, "git")]` | {class}`Tuple` of ({data}`INT`, {data}`STRING`) |175| `{1, 2}` or `frozenset({1, 2})` | {data}`STRING` |176| `{"a": 1}` | {data}`STRING` |177| {class}`uuid.UUID` or {class}`datetime.datetime` | {data}`STRING` |178| `b"git"`, or any other object | {data}`STRING` |179180A `list` or `tuple` gives the type of its **first item only**, so `[1, "git"]` gives181{data}`INT` and the second item is converted with it. A first item that is itself a182`list` or `tuple` gives a {class}`Tuple`, which also sets `nargs`.183184A `set`, a `frozenset`, a `dict`, and a type Click ships but does not guess, such as185{class}`uuid.UUID`, all land in the last group. Their default is converted with186{data}`STRING`, so the command receives the `str()` form of the value.187188```{eval-rst}189.. click:example::190191 @click.command()192 @click.option('--count', default=5)193 @click.option('--tag', default={'git'})194 def show(count, tag):195 click.echo(f"count is {type(count).__name__}, tag is {type(tag).__name__}")196197.. click:run::198199 invoke(show, args=[])200```201202When `type` is given a callable Click does not recognize, that callable is called on the203string coming from the command line, and a `ValueError` it raises is reported as a bad204parameter. A container is rarely useful there, because calling it on a string splits the205string: `set` turns `"git"` into `{"g", "i", "t"}`. Pass a {class}`ParamType` instead,206as described in [](#how-to-implement-custom-types).207Move Parameter-types doc from reST to MyST (#3041)Rowlando13before adoption23780fa
lines 208–213why, one step back208## How to Implement Custom Types209210To implement a custom type, you need to subclass the {class}`ParamType` class. For simple cases, passing a Python211function that fails with a `ValueError` is also supported, though discouraged. Override the {meth}`~ParamType.convert`212method to convert the value from a string to the correct type.213`ParamType` and other typing improvements (#3371)Rowlando13before adoption8a2b489
lines 214–217why, one step back214{class}`ParamType` is generic in the converted value type: parameterize it with215the type returned by `convert` so that consumers (and type checkers) can rely216on the narrowed return type.217Move Parameter-types doc from reST to MyST (#3041)Rowlando13before adoption23780fa
lines 218–223why, one step back218The following code implements an integer type that accepts hex and octal numbers in addition to normal integers, and219converts them into regular integers.220221```python222import click223`ParamType` and other typing improvements (#3371)Rowlando13before adoption8a2b489
lines 224–225why, one step back224225class BasedIntParamType(click.ParamType[int]):Move Parameter-types doc from reST to MyST (#3041)Rowlando13before adoption23780fa
lines 226–227why, one step back226 name = "integer"227`ParamType` and other typing improvements (#3371)Rowlando13before adoption8a2b489
line 228why, one step back228 def convert(self, value, param, ctx) -> int:Move Parameter-types doc from reST to MyST (#3041)Rowlando13before adoption23780fa
lines 229–240why, one step back229 if isinstance(value, int):230 return value231232 try:233 if value[:2].lower() == "0x":234 return int(value[2:], 16)235 elif value[:1] == "0":236 return int(value, 8)237 return int(value, 10)238 except ValueError:239 self.fail(f"{value!r} is not a valid integer", param, ctx)240`ParamType` and other typing improvements (#3371)Rowlando13before adoption8a2b489
line 241why, one step back241Move Parameter-types doc from reST to MyST (#3041)Rowlando13before adoption23780fa
lines 242–250why, one step back242BASED_INT = BasedIntParamType()243```244245The {attr}`~ParamType.name` attribute is optional and is used for documentation. Call {meth}`~ParamType.fail` if246conversion fails. The `param` and `ctx` arguments may be `None` in some cases such as prompts.247248Values from user input or the command line will be strings, but default values and Python arguments may already be the249correct type. The custom type should check at the top if the value is already valid and pass it through to support those250cases.`ParamType` and other typing improvements (#3371)Rowlando13before adoption8a2b489
lines 251–257why, one step back251252```{versionchanged} 8.4.0253{class}`ParamType` is now a generic abstract base class. Parameterize it with254the converted value type ({class}`!ParamType[int]` for an integer-returning255type) so that {meth}`~ParamType.convert` and downstream consumers carry the256narrowed type.257```