Move Parameter-types doc from reST to MyST (#3041)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Rowlando13 · committed by GitHub · parents a97412d, 338fa44 · Browse files · 2 files·+186 added−181 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
2 files+186 added−181 removed
- other:+186 added−181 removed
Provenance
- Commit
23780fa- Tree
3c2a16e- Author
Rowlando13 <67291205+Rowlando13@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent 1
a97412d- Parent 2
338fa44
2 files changed+186 added−181 removed
added:docs/parameter-types.md+186 added
1+(parameter-types)=2+3+# Parameter Types4+5+```{currentmodule} click6+```7+8+When the parameter type is set using `type`, Click will leverage the type to make your life easier, for example adding9+data to your help pages. Most examples are done with options, but types are available to options and arguments.10+11+```{contents}12+---13+depth: 214+local: true15+---16+```17+18+## Built-in Types Examples19+20+(choice-opts)=21+22+### Choice23+24+Sometimes, you want to have a parameter be a choice of a list of values. In that case you can use {class}`Choice` type.25+It can be instantiated with a list of valid values. The originally passed choice will be returned, not the str passed on26+the command line. Token normalization functions and `case_sensitive=False` can cause the two to be different but still27+match. {meth}`Choice.normalize_choice` for more info.28+29+30+Example:31+32+```{eval-rst}33+.. click:example::34+35+ import enum36+37+ class HashType(enum.Enum):38+ MD5 = enum.auto()39+ SHA1 = enum.auto()40+41+ @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)46+47+What it looks like:48+49+.. click:run::50+51+ 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+```59+60+Any iterable may be passed to {class}`Choice`. If an `Enum` is passed, the names of the enum members will be used as61+valid choices.62+63+Choices work with options that have `multiple=True`. If a `default` value is given with `multiple=True`, it should be a64+list or tuple of valid choices.65+66+Choices should be unique after normalization, see {meth}`Choice.normalize_choice` for more info.67+68+```{versionchanged} 7.169+The resulting value from an option will always be one of the originally passed choices70+regardless of `case_sensitive`.71+```72+73+(ranges)=74+75+### Int and Float Ranges76+77+The {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`.79+80+If `min` or `max` is omitted, that side is *unbounded*. Any value in that direction is accepted. By default, both bounds81+are *closed*, which means the boundary value is included in the accepted range. `min_open` and `max_open` can be used to82+exclude that boundary from the range.83+84+If `clamp` mode is enabled, a value that is outside the range is set to the boundary instead of failing. For example,85+the range `0, 5` would return `5` for the value `10`, or `0` for the value `-1`. When using {class}`FloatRange`, `clamp`86+can only be enabled if both bounds are *closed* (the default).87+88+```{eval-rst}89+.. click:example::90+91+ @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)96+97+.. click:run::98+99+ invoke(repeat, args=['--count=100', '--digit=5'])100+ invoke(repeat, args=['--count=6', '--digit=12'])101+```102+103+## Built-in Types Listing104+105+The supported parameter {ref}`click-api-types` are106+107+- `str` / {data}`click.STRING`: The default parameter type which indicates unicode strings.108+109+- `int` / {data}`click.INT`: A parameter that only accepts integers.110+111+- `float` / {data}`click.FLOAT`: A parameter that only accepts floating point values.112+113+- `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`.116+117+- {data}`click.UUID`: A parameter that accepts UUID values. This is not automatically guessed but represented as118+ {class}`uuid.UUID`.119+120+```{eval-rst}121+* .. autoclass:: Choice122+ :noindex:123+```124+125+```{eval-rst}126+* .. autoclass:: DateTime127+ :noindex:128+```129+130+```{eval-rst}131+* .. autoclass:: File132+ :noindex:133+```134+135+```{eval-rst}136+* .. autoclass:: FloatRange137+ :noindex:138+```139+140+```{eval-rst}141+* .. autoclass:: IntRange142+ :noindex:143+```144+145+```{eval-rst}146+* .. autoclass:: Path147+ :noindex:148+```149+150+## How to Implement Custom Types151+152+To implement a custom type, you need to subclass the {class}`ParamType` class. For simple cases, passing a Python153+function that fails with a `ValueError` is also supported, though discouraged. Override the {meth}`~ParamType.convert`154+method to convert the value from a string to the correct type.155+156+The following code implements an integer type that accepts hex and octal numbers in addition to normal integers, and157+converts them into regular integers.158+159+```python160+import click161+162+class BasedIntParamType(click.ParamType):163+ name = "integer"164+165+ def convert(self, value, param, ctx):166+ if isinstance(value, int):167+ return value168+169+ 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)177+178+BASED_INT = BasedIntParamType()179+```180+181+The {attr}`~ParamType.name` attribute is optional and is used for documentation. Call {meth}`~ParamType.fail` if182+conversion fails. The `param` and `ctx` arguments may be `None` in some cases such as prompts.183+184+Values from user input or the command line will be strings, but default values and Python arguments may already be the185+correct type. The custom type should check at the top if the value is already valid and pass it through to support those186+cases.deleted:docs/parameter-types.rst-181 removed
1-.. _parameter-types:2-3-Parameter Types4-==================5-6-.. currentmodule:: click7-8-When the parameter type is set using ``type``, Click will leverage the type to make your life easier, for example adding data to your help pages. Most examples are done with options, but types are available to options and arguments.9-10-.. contents::11- :depth: 212- :local:13-14-Built-in Types Examples15-------------------------16-17-.. _choice-opts:18-19-Choice20-^^^^^^^^^^^^^^^^^^^^^^21-22-Sometimes, you want to have a parameter be a choice of a list of values.23-In that case you can use :class:`Choice` type. It can be instantiated24-with a list of valid values. The originally passed choice will be returned,25-not the str passed on the command line. Token normalization functions and26-``case_sensitive=False`` can cause the two to be different but still match.27-:meth:`Choice.normalize_choice` for more info.28-29-Example:30-31-.. click:example::32-33- import enum34-35- class HashType(enum.Enum):36- MD5 = enum.auto()37- SHA1 = enum.auto()38-39- @click.command()40- @click.option('--hash-type',41- type=click.Choice(HashType, case_sensitive=False))42- def digest(hash_type: HashType):43- click.echo(hash_type)44-45-What it looks like:46-47-.. click:run::48-49- invoke(digest, args=['--hash-type=MD5'])50- println()51- invoke(digest, args=['--hash-type=md5'])52- println()53- invoke(digest, args=['--hash-type=foo'])54- println()55- invoke(digest, args=['--help'])56-57-Any iterable may be passed to :class:`Choice`. If an ``Enum`` is passed, the58-names of the enum members will be used as valid choices.59-60-Choices work with options that have ``multiple=True``. If a ``default``61-value is given with ``multiple=True``, it should be a list or tuple of62-valid choices.63-64-Choices should be unique after normalization, see65-:meth:`Choice.normalize_choice` for more info.66-67-.. versionchanged:: 7.168- The resulting value from an option will always be one of the69- originally passed choices regardless of ``case_sensitive``.70-71-.. _ranges:72-73-Int and Float Ranges74-^^^^^^^^^^^^^^^^^^^^^^^75-76-The :class:`IntRange` type extends the :data:`INT` type to ensure the77-value is contained in the given range. The :class:`FloatRange` type does78-the same for :data:`FLOAT`.79-80-If ``min`` or ``max`` is omitted, that side is *unbounded*. Any value in81-that direction is accepted. By default, both bounds are *closed*, which82-means the boundary value is included in the accepted range. ``min_open``83-and ``max_open`` can be used to exclude that boundary from the range.84-85-If ``clamp`` mode is enabled, a value that is outside the range is set86-to the boundary instead of failing. For example, the range ``0, 5``87-would return ``5`` for the value ``10``, or ``0`` for the value ``-1``.88-When using :class:`FloatRange`, ``clamp`` can only be enabled if both89-bounds are *closed* (the default).90-91-.. click:example::92-93- @click.command()94- @click.option("--count", type=click.IntRange(0, 20, clamp=True))95- @click.option("--digit", type=click.IntRange(0, 9))96- def repeat(count, digit):97- click.echo(str(digit) * count)98-99-.. click:run::100-101- invoke(repeat, args=['--count=100', '--digit=5'])102- invoke(repeat, args=['--count=6', '--digit=12'])103-104-105-Built-in Types Listing106------------------------107-The supported parameter :ref:`click-api-types` are:108-109-* ``str`` / :data:`click.STRING`: The default parameter type which indicates unicode strings.110-111-* ``int`` / :data:`click.INT`: A parameter that only accepts integers.112-113-* ``float`` / :data:`click.FLOAT`: A parameter that only accepts floating point values.114-115-* ``bool`` / :data:`click.BOOL`: A parameter that accepts boolean values. This is automatically used116- for boolean flags. The string values "1", "true", "t", "yes", "y",117- and "on" convert to ``True``. "0", "false", "f", "no", "n", and118- "off" convert to ``False``.119-120-* :data:`click.UUID`:121- A parameter that accepts UUID values. This is not automatically122- guessed but represented as :class:`uuid.UUID`.123-124-* .. autoclass:: Choice125- :noindex:126-127-* .. autoclass:: DateTime128- :noindex:129-130-* .. autoclass:: File131- :noindex:132-133-* .. autoclass:: FloatRange134- :noindex:135-136-* .. autoclass:: IntRange137- :noindex:138-139-* .. autoclass:: Path140- :noindex:141-142-How to Implement Custom Types143--------------------------------144-145-To implement a custom type, you need to subclass the :class:`ParamType` class. For simple cases, passing a Python function that fails with a `ValueError` is also supported, though discouraged. Override the :meth:`~ParamType.convert` method to convert the value from a string to the correct type.146-147-The following code implements an integer type that accepts hex and octal148-numbers in addition to normal integers, and converts them into regular149-integers.150-151-.. code-block:: python152-153- import click154-155- class BasedIntParamType(click.ParamType):156- name = "integer"157-158- def convert(self, value, param, ctx):159- if isinstance(value, int):160- return value161-162- try:163- if value[:2].lower() == "0x":164- return int(value[2:], 16)165- elif value[:1] == "0":166- return int(value, 8)167- return int(value, 10)168- except ValueError:169- self.fail(f"{value!r} is not a valid integer", param, ctx)170-171- BASED_INT = BasedIntParamType()172-173-The :attr:`~ParamType.name` attribute is optional and is used for174-documentation. Call :meth:`~ParamType.fail` if conversion fails. The175-``param`` and ``ctx`` arguments may be ``None`` in some cases such as176-prompts.177-178-Values from user input or the command line will be strings, but default179-values and Python arguments may already be the correct type. The custom180-type should check at the top if the value is already valid and pass it181-through to support those cases.