parameter-types.md
This file
Path
docs/parameter-types.md
186 lines · 5.6 KiB · Markdown
Last changed by
Move Parameter-types doc from reST to MyST (#3041)Rowlando13before adoption23780fa
History of this fileTake it
Move Parameter-types doc from reST to MyST (#3041)Rowlando13before adoption23780fa
lines 1–186why, 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```7273(ranges)=7475### Int and Float Ranges7677The {class}`IntRange` type extends the {data}`INT` type to ensure the value is contained in the given range. The78{class}`FloatRange` type does the same for {data}`FLOAT`.7980If `min` or `max` is omitted, that side is *unbounded*. Any value in that direction is accepted. By default, both bounds81are *closed*, which means the boundary value is included in the accepted range. `min_open` and `max_open` can be used to82exclude that boundary from the range.8384If `clamp` mode is enabled, a value that is outside the range is set to the boundary instead of failing. For example,85the range `0, 5` would return `5` for the value `10`, or `0` for the value `-1`. When using {class}`FloatRange`, `clamp`86can only be enabled if both bounds are *closed* (the default).8788```{eval-rst}89.. click:example::9091 @click.command()92 @click.option("--count", type=click.IntRange(0, 20, clamp=True))93 @click.option("--digit", type=click.IntRange(0, 9))94 def repeat(count, digit):95 click.echo(str(digit) * count)9697.. click:run::9899 invoke(repeat, args=['--count=100', '--digit=5'])100 invoke(repeat, args=['--count=6', '--digit=12'])101```102103## Built-in Types Listing104105The supported parameter {ref}`click-api-types` are106107- `str` / {data}`click.STRING`: The default parameter type which indicates unicode strings.108109- `int` / {data}`click.INT`: A parameter that only accepts integers.110111- `float` / {data}`click.FLOAT`: A parameter that only accepts floating point values.112113- `bool` / {data}`click.BOOL`: A parameter that accepts boolean values. This is automatically used for boolean flags.114 The string values "1", "true", "t", "yes", "y", and "on" convert to `True`. "0", "false", "f", "no", "n", and "off"115 convert to `False`.116117- {data}`click.UUID`: A parameter that accepts UUID values. This is not automatically guessed but represented as118 {class}`uuid.UUID`.119120```{eval-rst}121* .. autoclass:: Choice122 :noindex:123```124125```{eval-rst}126* .. autoclass:: DateTime127 :noindex:128```129130```{eval-rst}131* .. autoclass:: File132 :noindex:133```134135```{eval-rst}136* .. autoclass:: FloatRange137 :noindex:138```139140```{eval-rst}141* .. autoclass:: IntRange142 :noindex:143```144145```{eval-rst}146* .. autoclass:: Path147 :noindex:148```149150## How to Implement Custom Types151152To implement a custom type, you need to subclass the {class}`ParamType` class. For simple cases, passing a Python153function that fails with a `ValueError` is also supported, though discouraged. Override the {meth}`~ParamType.convert`154method to convert the value from a string to the correct type.155156The following code implements an integer type that accepts hex and octal numbers in addition to normal integers, and157converts them into regular integers.158159```python160import click161162class BasedIntParamType(click.ParamType):163 name = "integer"164165 def convert(self, value, param, ctx):166 if isinstance(value, int):167 return value168169 try:170 if value[:2].lower() == "0x":171 return int(value[2:], 16)172 elif value[:1] == "0":173 return int(value, 8)174 return int(value, 10)175 except ValueError:176 self.fail(f"{value!r} is not a valid integer", param, ctx)177178BASED_INT = BasedIntParamType()179```180181The {attr}`~ParamType.name` attribute is optional and is used for documentation. Call {meth}`~ParamType.fail` if182conversion fails. The `param` and `ctx` arguments may be `None` in some cases such as prompts.183184Values from user input or the command line will be strings, but default values and Python arguments may already be the185correct type. The custom type should check at the top if the value is already valid and pass it through to support those186cases.