rename extension from .rst to .md
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by denuoweb · committed by denuoweb · parent bb11331 · Browse files · 2 files·+181 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+181 added−181 removed
- other:+181 added−181 removed
Provenance
- Commit
868230d- Tree
7d1a20f- Author
denuoweb <jaron@rosenau.info>- Committer
denuoweb <jaron@rosenau.info>- Parent
bb11331
2 files changed+181 added−181 removed
added:docs/parameter-types.md+181 added
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.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.