Skip to content
Myr

parameter-types.rst

This file

Path

docs/parameter-types.rst

182 lines · 5.7 KiB

Last changed by

Rewrite first half of options docs (#2825)Rowlando13before adoption82089af

History of this file

Take it

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 = 'MD5'37        SHA1 = 'SHA1'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'])5657Since version 8.2.0 any iterable may be passed to :class:`Choice`, here58an ``Enum`` is used which will result in all enum values to be valid59choices.6061Choices work with options that have ``multiple=True``. If a ``default``62value is given with ``multiple=True``, it should be a list or tuple of63valid choices.6465Choices should be unique after normalization, see66:meth:`Choice.normalize_choice` for more info.6768.. versionchanged:: 7.169    The resulting value from an option will always be one of the70    originally passed choices regardless of ``case_sensitive``.7172.. _ranges:7374Int and Float Ranges75^^^^^^^^^^^^^^^^^^^^^^^7677The :class:`IntRange` type extends the :data:`INT` type to ensure the78value is contained in the given range. The :class:`FloatRange` type does79the same for :data:`FLOAT`.8081If ``min`` or ``max`` is omitted, that side is *unbounded*. Any value in82that direction is accepted. By default, both bounds are *closed*, which83means the boundary value is included in the accepted range. ``min_open``84and ``max_open`` can be used to exclude that boundary from the range.8586If ``clamp`` mode is enabled, a value that is outside the range is set87to the boundary instead of failing. For example, the range ``0, 5``88would return ``5`` for the value ``10``, or ``0`` for the value ``-1``.89When using :class:`FloatRange`, ``clamp`` can only be enabled if both90bounds are *closed* (the default).9192.. click:example::9394    @click.command()95    @click.option("--count", type=click.IntRange(0, 20, clamp=True))96    @click.option("--digit", type=click.IntRange(0, 9))97    def repeat(count, digit):98        click.echo(str(digit) * count)99100.. click:run::101102    invoke(repeat, args=['--count=100', '--digit=5'])103    invoke(repeat, args=['--count=6', '--digit=12'])104105106Built-in Types Listing107-----------------------108The supported parameter :ref:`click-api-types` are:109110*   ``str`` / :data:`click.STRING`: The default parameter type which indicates unicode strings.111112*   ``int`` / :data:`click.INT`: A parameter that only accepts integers.113114*   ``float`` / :data:`click.FLOAT`: A parameter that only accepts floating point values.115116*   ``bool`` / :data:`click.BOOL`: A parameter that accepts boolean values. This is automatically used117    for boolean flags. The string values "1", "true", "t", "yes", "y",118    and "on" convert to ``True``. "0", "false", "f", "no", "n", and119    "off" convert to ``False``.120121*   :data:`click.UUID`:122    A parameter that accepts UUID values.  This is not automatically123    guessed but represented as :class:`uuid.UUID`.124125*   .. autoclass:: Choice126       :noindex:127128*   .. autoclass:: DateTime129       :noindex:130131*   .. autoclass:: File132       :noindex:133134*   .. autoclass:: FloatRange135       :noindex:136137*   .. autoclass:: IntRange138       :noindex:139140*   .. autoclass:: Path141       :noindex:142143How to Implement Custom Types144-------------------------------145146To 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.147148The following code implements an integer type that accepts hex and octal149numbers in addition to normal integers, and converts them into regular150integers.151152.. code-block:: python153154    import click155156    class BasedIntParamType(click.ParamType):157        name = "integer"158159        def convert(self, value, param, ctx):160            if isinstance(value, int):161                return value162163            try:164                if value[:2].lower() == "0x":165                    return int(value[2:], 16)166                elif value[:1] == "0":167                    return int(value, 8)168                return int(value, 10)169            except ValueError:170                self.fail(f"{value!r} is not a valid integer", param, ctx)171172    BASED_INT = BasedIntParamType()173174The :attr:`~ParamType.name` attribute is optional and is used for175documentation. Call :meth:`~ParamType.fail` if conversion fails. The176``param`` and ``ctx`` arguments may be ``None`` in some cases such as177prompts.178179Values from user input or the command line will be strings, but default180values and Python arguments may already be the correct type. The custom181type should check at the top if the value is already valid and pass it182through to support those cases.