parameter-types.md
This file
Path
docs/parameter-types.md
205 lines · 6.2 KiB · Markdown
Last changed by
Merge branch 'main' into fix-default-map-nargsRowlando13before adoptiona014796
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```72Merge branch 'main' into fix-default-map-nargsRowlando13before adoptiona014796
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–161why, 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```155156## How to Implement Custom Types157158To implement a custom type, you need to subclass the {class}`ParamType` class. For simple cases, passing a Python159function that fails with a `ValueError` is also supported, though discouraged. Override the {meth}`~ParamType.convert`160method to convert the value from a string to the correct type.161Merge branch 'main' into fix-default-map-nargsRowlando13before adoptiona014796
lines 162–165why, one step back162{class}`ParamType` is generic in the converted value type: parameterize it with163the type returned by `convert` so that consumers (and type checkers) can rely164on the narrowed return type.165Move Parameter-types doc from reST to MyST (#3041)Rowlando13before adoption23780fa
lines 166–171why, one step back166The following code implements an integer type that accepts hex and octal numbers in addition to normal integers, and167converts them into regular integers.168169```python170import click171Merge branch 'main' into fix-default-map-nargsRowlando13before adoptiona014796
lines 172–173why, one step back172173class BasedIntParamType(click.ParamType[int]):Move Parameter-types doc from reST to MyST (#3041)Rowlando13before adoption23780fa
lines 174–175why, one step back174 name = "integer"175Merge branch 'main' into fix-default-map-nargsRowlando13before adoptiona014796
line 176why, one step back176 def convert(self, value, param, ctx) -> int:Move Parameter-types doc from reST to MyST (#3041)Rowlando13before adoption23780fa
lines 177–188why, one step back177 if isinstance(value, int):178 return value179180 try:181 if value[:2].lower() == "0x":182 return int(value[2:], 16)183 elif value[:1] == "0":184 return int(value, 8)185 return int(value, 10)186 except ValueError:187 self.fail(f"{value!r} is not a valid integer", param, ctx)188Merge branch 'main' into fix-default-map-nargsRowlando13before adoptiona014796
line 189why, one step back189Move Parameter-types doc from reST to MyST (#3041)Rowlando13before adoption23780fa
lines 190–198why, one step back190BASED_INT = BasedIntParamType()191```192193The {attr}`~ParamType.name` attribute is optional and is used for documentation. Call {meth}`~ParamType.fail` if194conversion fails. The `param` and `ctx` arguments may be `None` in some cases such as prompts.195196Values from user input or the command line will be strings, but default values and Python arguments may already be the197correct type. The custom type should check at the top if the value is already valid and pass it through to support those198cases.Merge branch 'main' into fix-default-map-nargsRowlando13before adoptiona014796
lines 199–205why, one step back199200```{versionchanged} 8.4.0201{class}`ParamType` is now a generic abstract base class. Parameterize it with202the converted value type ({class}`!ParamType[int]` for an integer-returning203type) so that {meth}`~ParamType.convert` and downstream consumers carry the204narrowed type.205```