Move Parameter-types doc from reST to MyST
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by denuoweb · committed by denuoweb · parent 868230d · Browse files · 1 file·+93 added−88 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
1 file+93 added−88 removed
- other:+93 added−88 removed
Provenance
- Commit
d502a68- Tree
51af628- Author
denuoweb <jaron@rosenau.info>- Committer
denuoweb <jaron@rosenau.info>- Parent
868230d
1 file changed+93 added−88 removed
modified:docs/parameter-types.md+93 added-88 removed
11234346567889101011121112131415161714151819172021192022232223242526272425262728293031323334353617 unmodified lines545556575859575859606160616264656364656768696667716869707172737473747677787576808182837778798586878889808182838485868788899091924 unmodified lines979899100101102103104105106107105106109107108111109110113111112115116117118113114115116120121122117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149142143150151145152153154155147148149156157158151159160161153162163164155156165166167168158159160169170171172173174175176177162163164165166167168169178179180171181182183173174175176177178179180181184185186.. _parameter-types:(parameter-types)=
Parameter Types==================# Parameter Types
.. currentmodule:: click```{currentmodule} click```
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.When the parameter type is set using `type`, Click will leverage the type to make your life easier, for example addingdata to your help pages. Most examples are done with options, but types are available to options and arguments.
.. contents:: :depth: 2 :local:```{contents}---depth: 2local: true---```
Built-in Types Examples------------------------## Built-in Types Examples
.. _choice-opts:(choice-opts)=
Choice^^^^^^^^^^^^^^^^^^^^^^### Choice
Sometimes, you want to have a parameter be a choice of a list of values.In that case you can use :class:`Choice` type. It can be instantiatedwith a list of valid values. The originally passed choice will be returned,not the str passed on the command line. Token normalization functions and``case_sensitive=False`` can cause the two to be different but still match.:meth:`Choice.normalize_choice` for more info.Sometimes, you want to have a parameter be a choice of a list of values. In that case you can use {class}`Choice` type.It can be instantiated with a list of valid values. The originally passed choice will be returned, not the str passed onthe command line. Token normalization functions and `case_sensitive=False` can cause the two to be different but stillmatch. {meth}`Choice.normalize_choice` for more info.
Example:
```{eval-rst}.. click:example::
import enum
17 unmodified lines println() invoke(digest, args=['--hash-type=foo']) println() invoke(digest, args=['--help'])```
Any iterable may be passed to :class:`Choice`. If an ``Enum`` is passed, thenames of the enum members will be used as valid choices.
Choices work with options that have ``multiple=True``. If a ``default``value is given with ``multiple=True``, it should be a list or tuple ofAny iterable may be passed to {class}`Choice`. If an `Enum` is passed, the names of the enum members will be used asvalid choices.
Choices should be unique after normalization, see:meth:`Choice.normalize_choice` for more info.Choices work with options that have `multiple=True`. If a `default` value is given with `multiple=True`, it should be alist or tuple of valid choices.
.. versionchanged:: 7.1 The resulting value from an option will always be one of the originally passed choices regardless of ``case_sensitive``.Choices should be unique after normalization, see {meth}`Choice.normalize_choice` for more info.
.. _ranges:```{versionchanged} 7.1The resulting value from an option will always be one of the originally passed choicesregardless of `case_sensitive`.```
Int and Float Ranges^^^^^^^^^^^^^^^^^^^^^^^(ranges)=
The :class:`IntRange` type extends the :data:`INT` type to ensure thevalue is contained in the given range. The :class:`FloatRange` type doesthe same for :data:`FLOAT`.### Int and Float Ranges
If ``min`` or ``max`` is omitted, that side is *unbounded*. Any value inthat direction is accepted. By default, both bounds are *closed*, whichmeans the boundary value is included in the accepted range. ``min_open``and ``max_open`` can be used to exclude that boundary from the range.The {class}`IntRange` type extends the {data}`INT` type to ensure the value is contained in the given range. The{class}`FloatRange` type does the same for {data}`FLOAT`.
If ``clamp`` mode is enabled, a value that is outside the range is setto the boundary instead of failing. For example, the range ``0, 5``would return ``5`` for the value ``10``, or ``0`` for the value ``-1``.When using :class:`FloatRange`, ``clamp`` can only be enabled if bothbounds are *closed* (the default).If `min` or `max` is omitted, that side is *unbounded*. Any value in that direction is accepted. By default, both boundsare *closed*, which means the boundary value is included in the accepted range. `min_open` and `max_open` can be used toexclude that boundary from the range.
If `clamp` mode is enabled, a value that is outside the range is set to the boundary instead of failing. For example,the range `0, 5` would return `5` for the value `10`, or `0` for the value `-1`. When using {class}`FloatRange`, `clamp`can only be enabled if both bounds are *closed* (the default).
```{eval-rst}.. click:example::
@click.command() @click.option("--count", type=click.IntRange(0, 20, clamp=True))4 unmodified lines.. click:run::
invoke(repeat, args=['--count=100', '--digit=5']) invoke(repeat, args=['--count=6', '--digit=12'])```
## Built-in Types Listing
Built-in Types Listing-----------------------The supported parameter :ref:`click-api-types` are:The supported parameter {ref}`click-api-types` are
* ``str`` / :data:`click.STRING`: The default parameter type which indicates unicode strings.- `str` / {data}`click.STRING`: The default parameter type which indicates unicode strings.
* ``int`` / :data:`click.INT`: A parameter that only accepts integers.- `int` / {data}`click.INT`: A parameter that only accepts integers.
* ``float`` / :data:`click.FLOAT`: A parameter that only accepts floating point values.- `float` / {data}`click.FLOAT`: A parameter that only accepts floating point values.
* ``bool`` / :data:`click.BOOL`: A parameter that accepts boolean values. This is automatically used for boolean flags. The string values "1", "true", "t", "yes", "y", and "on" convert to ``True``. "0", "false", "f", "no", "n", and "off" convert to ``False``.- `bool` / {data}`click.BOOL`: A parameter that accepts boolean values. This is automatically used for boolean flags. The string values "1", "true", "t", "yes", "y", and "on" convert to `True`. "0", "false", "f", "no", "n", and "off" convert to `False`.
* :data:`click.UUID`: A parameter that accepts UUID values. This is not automatically guessed but represented as :class:`uuid.UUID`.- {data}`click.UUID`: A parameter that accepts UUID values. This is not automatically guessed but represented as {class}`uuid.UUID`.
```{eval-rst}* .. autoclass:: Choice :noindex:```
```{eval-rst}* .. autoclass:: DateTime :noindex:```
```{eval-rst}* .. autoclass:: File :noindex:```
```{eval-rst}* .. autoclass:: FloatRange :noindex:```
```{eval-rst}* .. autoclass:: IntRange :noindex:```
```{eval-rst}* .. autoclass:: Path :noindex:```
How to Implement Custom Types-------------------------------## How to Implement Custom Types
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.To implement a custom type, you need to subclass the {class}`ParamType` class. For simple cases, passing a Pythonfunction 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.
The following code implements an integer type that accepts hex and octalnumbers in addition to normal integers, and converts them into regularintegers.The following code implements an integer type that accepts hex and octal numbers in addition to normal integers, andconverts them into regular integers.
.. code-block:: python```pythonimport click
import clickclass BasedIntParamType(click.ParamType): name = "integer"
class BasedIntParamType(click.ParamType): name = "integer" def convert(self, value, param, ctx): if isinstance(value, int): return value
def convert(self, value, param, ctx): if isinstance(value, int): return value try: if value[:2].lower() == "0x": return int(value[2:], 16) elif value[:1] == "0": return int(value, 8) return int(value, 10) except ValueError: self.fail(f"{value!r} is not a valid integer", param, ctx)
try: if value[:2].lower() == "0x": return int(value[2:], 16) elif value[:1] == "0": return int(value, 8) return int(value, 10) except ValueError: self.fail(f"{value!r} is not a valid integer", param, ctx)BASED_INT = BasedIntParamType()```
BASED_INT = BasedIntParamType()The {attr}`~ParamType.name` attribute is optional and is used for documentation. Call {meth}`~ParamType.fail` ifconversion fails. The `param` and `ctx` arguments may be `None` in some cases such as prompts.
The :attr:`~ParamType.name` attribute is optional and is used fordocumentation. Call :meth:`~ParamType.fail` if conversion fails. The``param`` and ``ctx`` arguments may be ``None`` in some cases such asprompts.
Values from user input or the command line will be strings, but defaultvalues and Python arguments may already be the correct type. The customtype should check at the top if the value is already valid and pass itthrough to support those cases.Values from user input or the command line will be strings, but default values and Python arguments may already be thecorrect type. The custom type should check at the top if the value is already valid and pass it through to support thosecases.No newline at end of file