Skip to content
Myr

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

2 files+181 added−181 removed

added:docs/parameter-types.md+181 added
1.. _parameter-types:23Parameter Types4==================56.. currentmodule:: click78When 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.910.. contents::11 :depth: 212 :local:1314Built-in Types Examples15------------------------1617.. _choice-opts:1819Choice20^^^^^^^^^^^^^^^^^^^^^^2122Sometimes, you want to have a parameter be a choice of a list of values.23In that case you can use :class:`Choice` type. It can be instantiated24with a list of valid values. The originally passed choice will be returned,25not 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.2829Example:3031.. click:example::3233 import enum3435 class HashType(enum.Enum):36 MD5 = enum.auto()37 SHA1 = enum.auto()3839 @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)4445What it looks like:4647.. click:run::4849 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'])5657Any iterable may be passed to :class:`Choice`. If an ``Enum`` is passed, the58names of the enum members will be used as valid choices.5960Choices work with options that have ``multiple=True``. If a ``default``61value is given with ``multiple=True``, it should be a list or tuple of62valid choices.6364Choices should be unique after normalization, see65:meth:`Choice.normalize_choice` for more info.6667.. versionchanged:: 7.168 The resulting value from an option will always be one of the69 originally passed choices regardless of ``case_sensitive``.7071.. _ranges:7273Int and Float Ranges74^^^^^^^^^^^^^^^^^^^^^^^7576The :class:`IntRange` type extends the :data:`INT` type to ensure the77value is contained in the given range. The :class:`FloatRange` type does78the same for :data:`FLOAT`.7980If ``min`` or ``max`` is omitted, that side is *unbounded*. Any value in81that direction is accepted. By default, both bounds are *closed*, which82means the boundary value is included in the accepted range. ``min_open``83and ``max_open`` can be used to exclude that boundary from the range.8485If ``clamp`` mode is enabled, a value that is outside the range is set86to the boundary instead of failing. For example, the range ``0, 5``87would return ``5`` for the value ``10``, or ``0`` for the value ``-1``.88When using :class:`FloatRange`, ``clamp`` can only be enabled if both89bounds are *closed* (the default).9091.. click:example::9293 @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)9899.. click:run::100101 invoke(repeat, args=['--count=100', '--digit=5'])102 invoke(repeat, args=['--count=6', '--digit=12'])103104105Built-in Types Listing106-----------------------107The supported parameter :ref:`click-api-types` are:108109* ``str`` / :data:`click.STRING`: The default parameter type which indicates unicode strings.110111* ``int`` / :data:`click.INT`: A parameter that only accepts integers.112113* ``float`` / :data:`click.FLOAT`: A parameter that only accepts floating point values.114115* ``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``.119120* :data:`click.UUID`:121 A parameter that accepts UUID values. This is not automatically122 guessed but represented as :class:`uuid.UUID`.123124* .. autoclass:: Choice125 :noindex:126127* .. autoclass:: DateTime128 :noindex:129130* .. autoclass:: File131 :noindex:132133* .. autoclass:: FloatRange134 :noindex:135136* .. autoclass:: IntRange137 :noindex:138139* .. autoclass:: Path140 :noindex:141142How to Implement Custom Types143-------------------------------144145To 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.146147The following code implements an integer type that accepts hex and octal148numbers in addition to normal integers, and converts them into regular149integers.150151.. code-block:: python152153 import click154155 class BasedIntParamType(click.ParamType):156 name = "integer"157158 def convert(self, value, param, ctx):159 if isinstance(value, int):160 return value161162 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)170171 BASED_INT = BasedIntParamType()172173The :attr:`~ParamType.name` attribute is optional and is used for174documentation. Call :meth:`~ParamType.fail` if conversion fails. The175``param`` and ``ctx`` arguments may be ``None`` in some cases such as176prompts.177178Values from user input or the command line will be strings, but default179values and Python arguments may already be the correct type. The custom180type should check at the top if the value is already valid and pass it181through to support those cases.
deleted:docs/parameter-types.rst-181 removed
1.. _parameter-types:23Parameter Types4==================56.. currentmodule:: click78When 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.910.. contents::11 :depth: 212 :local:1314Built-in Types Examples15------------------------1617.. _choice-opts:1819Choice20^^^^^^^^^^^^^^^^^^^^^^2122Sometimes, you want to have a parameter be a choice of a list of values.23In that case you can use :class:`Choice` type. It can be instantiated24with a list of valid values. The originally passed choice will be returned,25not 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.2829Example:3031.. click:example::3233 import enum3435 class HashType(enum.Enum):36 MD5 = enum.auto()37 SHA1 = enum.auto()3839 @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)4445What it looks like:4647.. click:run::4849 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'])5657Any iterable may be passed to :class:`Choice`. If an ``Enum`` is passed, the58names of the enum members will be used as valid choices.5960Choices work with options that have ``multiple=True``. If a ``default``61value is given with ``multiple=True``, it should be a list or tuple of62valid choices.6364Choices should be unique after normalization, see65:meth:`Choice.normalize_choice` for more info.6667.. versionchanged:: 7.168 The resulting value from an option will always be one of the69 originally passed choices regardless of ``case_sensitive``.7071.. _ranges:7273Int and Float Ranges74^^^^^^^^^^^^^^^^^^^^^^^7576The :class:`IntRange` type extends the :data:`INT` type to ensure the77value is contained in the given range. The :class:`FloatRange` type does78the same for :data:`FLOAT`.7980If ``min`` or ``max`` is omitted, that side is *unbounded*. Any value in81that direction is accepted. By default, both bounds are *closed*, which82means the boundary value is included in the accepted range. ``min_open``83and ``max_open`` can be used to exclude that boundary from the range.8485If ``clamp`` mode is enabled, a value that is outside the range is set86to the boundary instead of failing. For example, the range ``0, 5``87would return ``5`` for the value ``10``, or ``0`` for the value ``-1``.88When using :class:`FloatRange`, ``clamp`` can only be enabled if both89bounds are *closed* (the default).9091.. click:example::9293 @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)9899.. click:run::100101 invoke(repeat, args=['--count=100', '--digit=5'])102 invoke(repeat, args=['--count=6', '--digit=12'])103104105Built-in Types Listing106-----------------------107The supported parameter :ref:`click-api-types` are:108109* ``str`` / :data:`click.STRING`: The default parameter type which indicates unicode strings.110111* ``int`` / :data:`click.INT`: A parameter that only accepts integers.112113* ``float`` / :data:`click.FLOAT`: A parameter that only accepts floating point values.114115* ``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``.119120* :data:`click.UUID`:121 A parameter that accepts UUID values. This is not automatically122 guessed but represented as :class:`uuid.UUID`.123124* .. autoclass:: Choice125 :noindex:126127* .. autoclass:: DateTime128 :noindex:129130* .. autoclass:: File131 :noindex:132133* .. autoclass:: FloatRange134 :noindex:135136* .. autoclass:: IntRange137 :noindex:138139* .. autoclass:: Path140 :noindex:141142How to Implement Custom Types143-------------------------------144145To 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.146147The following code implements an integer type that accepts hex and octal148numbers in addition to normal integers, and converts them into regular149integers.150151.. code-block:: python152153 import click154155 class BasedIntParamType(click.ParamType):156 name = "integer"157158 def convert(self, value, param, ctx):159 if isinstance(value, int):160 return value161162 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)170171 BASED_INT = BasedIntParamType()172173The :attr:`~ParamType.name` attribute is optional and is used for174documentation. Call :meth:`~ParamType.fail` if conversion fails. The175``param`` and ``ctx`` arguments may be ``None`` in some cases such as176prompts.177178Values from user input or the command line will be strings, but default179values and Python arguments may already be the correct type. The custom180type should check at the top if the value is already valid and pass it181through to support those cases.