Skip to content
Myr

Rewrite first half of options docs (#2825)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Rowlando13 · committed by GitHub · parent 4ece17a · Browse files · 7 files+419 added−399 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Trailers

  • Co-authored-by: Andreas Backx <andreas@backx.org>

Diff stats

7 files+419 added−399 removed

  • other:+419 added−399 removed

7 files+419 added−399 removed

modified:docs/api.rst+1 added
111 unmodified lines
112.. autoclass:: click.core.ParameterSource113 :members:114 :member-order: bysource115116.. _click-api-types:117118Types119-----120
91 unmodified lines
modified:docs/documentation.rst+36 added
106 unmodified lines
107.. click:run::108109 invoke(touch, args=['--help'])110111112Showing Defaults113---------------------------114To control the appearance of defaults pass ``show_default``.115116.. click:example::117118 @click.command()119 @click.option('--n', default=1, show_default=False, help='number of dots')120 def dots(n):121 click.echo('.' * n)122123.. click:run::124125 invoke(dots, args=['--help'])126127For single option boolean flags, the default remains hidden if the default value is False even if show default is true.128129.. click:example::130131 @click.command()132 @click.option('--n', default=1, show_default=True)133 @click.option("--gr", is_flag=True, show_default=True, default=False, help="Greet the world.")134 @click.option("--br", is_flag=True, show_default=True, default=True, help="Add a thematic break")135 def dots(n, gr, br):136 if gr:137 click.echo('Hello world!')138 click.echo('.' * n)139 if br:140 click.echo('-' * n)141142.. click:run::143144 invoke(dots, args=['--help'])145146147Click's Wrapping Behavior148----------------------------149Click's default wrapping ignores single new lines and rewraps the text based on the width of the terminal, to a maximum of 80 characters. In the example notice how the second grouping of three lines is rewrapped into a single paragraph.150
117 unmodified lines
modified:docs/index.rst+3 added-1 removed
70 unmodified lines
71 entry-points72 virtualenv73 setuptools74 parameters75 arguments75 parameter-types76 options77 option-decorators78 arguments79 commands80 documentation81 prompts82 complex
28 unmodified lines
added:docs/option-decorators.rst+80 added
1Options Shortcut Decorators2===========================34.. currentmodule:: click56For convenience commonly used combinations of options arguments are available as their own decorators.78.. contents::9 :depth: 210 :local:1112Password Option13------------------1415Click supports hidden prompts and asking for confirmation. This is16useful for password input:1718.. click:example::1920 import codecs2122 @click.command()23 @click.option(24 "--password", prompt=True, hide_input=True,25 confirmation_prompt=True26 )27 def encode(password):28 click.echo(f"encoded: {codecs.encode(password, 'rot13')}")2930.. click:run::3132 invoke(encode, input=['secret', 'secret'])3334Because this combination of parameters is quite common, this can also be35replaced with the :func:`password_option` decorator:3637.. code-block:: python3839 @click.command()40 @click.password_option()41 def encrypt(password):42 click.echo(f"encoded: to {codecs.encode(password, 'rot13')}")4344Confirmation Option45--------------------4647For dangerous operations, it's very useful to be able to ask a user for48confirmation. This can be done by adding a boolean ``--yes`` flag and49asking for confirmation if the user did not provide it and to fail in a50callback:5152.. click:example::5354 def abort_if_false(ctx, param, value):55 if not value:56 ctx.abort()5758 @click.command()59 @click.option('--yes', is_flag=True, callback=abort_if_false,60 expose_value=False,61 prompt='Are you sure you want to drop the db?')62 def dropdb():63 click.echo('Dropped all tables!')6465And what it looks like on the command line:6667.. click:run::6869 invoke(dropdb, input=['n'])70 invoke(dropdb, args=['--yes'])7172Because this combination of parameters is quite common, this can also be73replaced with the :func:`confirmation_option` decorator:7475.. click:example::7677 @click.command()78 @click.confirmation_option(prompt='Are you sure you want to drop the db?')79 def dropdb():80 click.echo('Dropped all tables!')
modified:docs/options.rst+114 added-314 removed
1.. _options:23Options4=======4=========56.. currentmodule:: click78Adding options to commands can be accomplished by the :func:`option`9decorator. Since options can come in various different versions, there10are a ton of parameters to configure their behavior. Options in click are11distinct from :ref:`positional arguments <arguments>`.8Adding options to commands can be accomplished with the :func:`option`9decorator. Options in Click are distinct from :ref:`positional arguments <arguments>`.1013Name Your Options14-----------------11Useful and often used kwargs are:1216Options have a name that will be used as the Python argument name when17calling the decorated function. This can be inferred from the option18names or given explicitly. Names are given as position arguments to the19decorator.13* ``default``: Passes a default.14* ``help``: Sets help message.15* ``nargs``: Sets the number of arguments.16* ``required``: Makes option required.17* ``type``: Sets :ref:`parameter-types`1821A name is chosen in the following order19.. contents::20 :depth: 221 :local:22231. If a name is not prefixed, it is used as the Python argument name24 and not treated as an option name on the command line.252. If there is at least one name prefixed with two dashes, the first26 one given is used as the name.273. The first name prefixed with one dash is used otherwise.23Option Decorator24-----------------25Click expects you to pass at least two positional arguments to the option decorator. They are option name and function argument name.2629To get the Python argument name, the chosen name is converted to lower30case, up to two dashes are removed as the prefix, and other dashes are31converted to underscores.27.. click:example::2833.. code-block:: python3429 @click.command()36 @click.option('-s', '--string-to-echo')30 @click.option('--string-to-echo', 'string_to_echo')31 def echo(string_to_echo):32 click.echo(string_to_echo)3340.. code-block:: python34.. click:run::3542 @click.command()43 @click.option('-s', '--string-to-echo', 'string')44 def echo(string):45 click.echo(string)36 invoke(echo, args=['--help'])3747- ``"-f", "--foo-bar"``, the name is ``foo_bar``48- ``"-x"``, the name is ``x``49- ``"-f", "--filename", "dest"``, the name is ``dest``50- ``"--CamelCase"``, the name is ``camelcase``51- ``"-f", "-fb"``, the name is ``f``52- ``"--f", "--foo-bar"``, the name is ``f``53- ``"---f"``, the name is ``_f``38However, if you don't pass in the function argument name, then Click will try to infer it. A simple way to name your option is by taking the function argument, adding two dashes to the front and converting underscores to dashes. In this case, Click will infer the function argument name correctly so you can add only the option name.3955Basic Value Options56-------------------5758The most basic option is a value option. These options accept one59argument which is a value. If no type is provided, the type of the default60value is used. If no default value is provided, the type is assumed to be61:data:`STRING`. Unless a name is explicitly specified, the name of the62parameter is the first long option defined; otherwise the first short one is63used. By default, options are not required, however to make an option required,64simply pass in `required=True` as an argument to the decorator.6540.. click:example::4142 @click.command()69 @click.option('--n', default=1)70 def dots(n):71 click.echo('.' * n)43 @click.option('--string-to-echo')44 def echo(string_to_echo):45 click.echo(string_to_echo)4673.. click:example::47.. click:run::4875 # How to make an option required76 @click.command()77 @click.option('--n', required=True, type=int)78 def dots(n):79 click.echo('.' * n)49 invoke(echo, args=['--string-to-echo', 'Hi!'])5081.. click:example::51More formally, Click will try to infer the function argument name by:5283 # How to use a Python reserved word such as `from` as a parameter84 @click.command()85 @click.option('--from', '-f', 'from_')86 @click.option('--to', '-t')87 def reserved_param_name(from_, to):88 click.echo(f"from {from_} to {to}")531. If a positional argument name does not have a prefix, it is chosen.542. If a positional argument name starts with with two dashes, the first one given is chosen.553. The first positional argument prefixed with one dash is chosen otherwise.5690And on the command line:57The chosen positional argument is converted to lower case, up to two dashes are removed from the beginning, and other dashes are converted to underscores to get the function argument name.5892.. click:run::59.. list-table:: Examples60 :widths: 15 1061 :header-rows: 16294 invoke(dots, args=['--n=2'])63 * - Decorator Arguments64 - Function Name65 * - ``"-f", "--foo-bar"``66 - foo_bar67 * - ``"-x"``68 - x69 * - ``"-f", "--filename", "dest"``70 - dest71 * - ``"--CamelCase"``72 - camelcase73 * - ``"-f", "-fb"``74 - f75 * - ``"--f", "--foo-bar"``76 - f77 * - ``"---f"``78 - _f7996In this case the option is of type :data:`INT` because the default value97is an integer.80Basic Example81---------------82A simple :class:`click.Option` takes one argument. This will assume the argument is not required. If the decorated function takes an positional argument then None is passed it. This will also assume the type is ``str``.8399To show the default values when showing command help, use ``show_default=True``10084.. click:example::8586 @click.command()104 @click.option('--n', default=1, show_default=True)105 def dots(n):106 click.echo('.' * n)87 @click.option('--text')88 def print_this(text):89 click.echo(text)909192.. click:run::93110 invoke(dots, args=['--help'])94 invoke(print_this, args=['--text=this'])95112For single option boolean flags, the default remains hidden if the default113value is False.96 invoke(print_this, args=[])9798.. click:run::99100 invoke(print_this, args=['--help'])101102103Setting a Default104---------------------------105Instead of setting the ``type``, you may set a default and Click will try to infer the type.106107.. click:example::108109 @click.command()118 @click.option('--n', default=1, show_default=True)119 @click.option("--gr", is_flag=True, show_default=True, default=False, help="Greet the world.")120 @click.option("--br", is_flag=True, show_default=True, default=True, help="Add a thematic break")121 def dots(n, gr, br):122 if gr:123 click.echo('Hello world!')110 @click.option('--n', default=1)111 def dots(n):112 click.echo('.' * n)125 if br:126 click.echo('-' * n)113114.. click:run::115130 invoke(dots, args=['--help'])116 invoke(dots, args=['--help'])117132118Multi Value Options119-------------------120136Sometimes, you have options that take more than one argument. For options,137only a fixed number of arguments is supported. This can be configured by138the ``nargs`` parameter. The values are then stored as a tuple.121To make an option take multiple values, pass in ``nargs``. Note only a fixed number of arguments is supported. The values are passed to the underlying function as a tuple.122123.. click:example::124125 @click.command()
1 unmodified line
127 def findme(pos):128 a, b = pos129 click.echo(f"{a} / {b}")130148And on the command line:149131.. click:run::132133 invoke(findme, args=['--pos', '2.0', '3.0'])134135136.. _tuple-type:137156Tuples as Multi Value Options138Multi Value Options as Tuples139-----------------------------140141.. versionadded:: 4.0142
30 unmodified lines
173174.. _multiple-options:175176Multiple Options195----------------177-----------------178197Similarly to ``nargs``, there is also the case of wanting to support a198parameter being provided multiple times and have all the values recorded --199not just the last one. For instance, ``git commit -m foo -m bar`` would200record two lines for the commit message: ``foo`` and ``bar``. This can be201accomplished with the ``multiple`` flag:179The multiple options format allows you to call the underlying function multiple times with one command line entry. If set, the default must be a list or tuple. Setting a string as a default will be interpreted as list of characters.180203Example:204181.. click:example::182183 @click.command()184 @click.option('--message', '-m', multiple=True)185 def commit(message):186 click.echo('\n'.join(message))187212And on the command line:213188.. click:run::189216 invoke(commit, args=['-m', 'foo', '-m', 'bar'])190 invoke(commit, args=['-m', 'foo', '-m', 'bar', '-m', 'here'])191218When passing a ``default`` with ``multiple=True``, the default value219must be a list or tuple, otherwise it will be interpreted as a list of220single characters.221222.. code-block:: python223224 @click.option("--format", multiple=True, default=["json"])225226192Counting193--------194To count the occurrence of an option pass in ``count=True``. If the option is not passed in, then the count is 0. Counting is commonly used for verbosity.195230In some very rare circumstances, it is interesting to use the repetition231of options to count an integer up. This can be used for verbosity flags,232for instance:233196.. click:example::197198 @click.command()199 @click.option('-v', '--verbose', count=True)200 def log(verbose):201 click.echo(f"Verbosity: {verbose}")202241And on the command line:242203.. click:run::204205 invoke(log, args=[])206 invoke(log, args=['-vvv'])207247Boolean Flags248-------------208Boolean209------------------------210250Boolean flags are options that can be enabled or disabled. This can be251accomplished by defining two flags in one go separated by a slash (``/``)252for enabling or disabling the option. (If a slash is in an option string,253Click automatically knows that it's a boolean flag and will pass254``is_flag=True`` implicitly.) Click always wants you to provide an enable255and disable flag so that you can change the default later.211Boolean options (boolean flags) take the value True or False. The simplest case sets the default value to ``False`` if the flag is not passed, and ``True`` if it is.212257Example:258213.. click:example::214215 import sys216217 @click.command()264 @click.option('--shout/--no-shout', default=False)218 @click.option('--shout', is_flag=True)219 def info(shout):220 rv = sys.platform221 if shout:222 rv = rv.upper() + '!!!!111'223 click.echo(rv)224271And on the command line:225226.. click:run::227275 invoke(info, args=['--shout'])276 invoke(info, args=['--no-shout'])228 invoke(info)229 invoke(info, args=['--shout'])230279If you really don't want an off-switch, you can just define one and280manually inform Click that something is a flag:231232To implement this more explicitly, pass in on-option ``/`` off-option. Click will automatically set ``is_flag=True``. Click always wants you to provide an enable233and disable flag so that you can change the default later.234235.. click:example::236237 import sys238239 @click.command()287 @click.option('--shout', is_flag=True)240 @click.option('--shout/--no-shout', default=False)241 def info(shout):242 rv = sys.platform243 if shout:244 rv = rv.upper() + '!!!!111'245 click.echo(rv)246294And on the command line:295247.. click:run::248298 invoke(info, args=['--shout'])249 invoke(info)250 invoke(info, args=['--shout'])251 invoke(info, args=['--no-shout'])252301Note that if a slash is contained in your option already (for instance, if302you use Windows-style parameters where ``/`` is the prefix character), you303can alternatively split the parameters through ``;`` instead:253If a forward slash(``/``) is contained in your option name already, you can split the parameters using ``;``. In Windows ``/`` is commonly used as the prefix character.254255.. click:example::256257 @click.command()258 @click.option('/debug;/no-debug')259 def log(debug):260 click.echo(f"debug={debug}")261312 if __name__ == '__main__':313 log()314262.. versionchanged:: 6.0263317If you want to define an alias for the second option only, then you will318need to use leading whitespace to disambiguate the format string:264If you want to define an alias for the second option only, then you will need to use leading whitespace to disambiguate the format string.265320Example:321266.. click:example::267268 import sys269270 @click.command()327 @click.option('--shout/--no-shout', ' /-S', default=False)271 @click.option('--shout/--no-shout', ' /-N', default=False)272 def info(shout):273 rv = sys.platform274 if shout:275 rv = rv.upper() + '!!!!111'
2 unmodified lines
278.. click:run::279280 invoke(info, args=['--help'])281282Flag Value283---------------284To have an flag pass a value to the underlying function set ``is_flag=True`` and set ``flag_value`` to the value desired. This can be used to create patterns like this:285286.. click:example::287288 import sys289290 @click.command()291 @click.option('--upper', 'transformation', flag_value='upper')292 @click.option('--lower', 'transformation', flag_value='lower')293 def info(transformation):294 click.echo(getattr(sys.platform, transformation)())295296.. click:run::297298 invoke(info, args=['--help'])299 invoke(info, args=['--upper'])300 invoke(info, args=['--lower'])301302Feature Switches339----------------303---------------------------304305In addition to boolean flags, there are also feature switches. These are306implemented by setting multiple options to the same parameter name and307defining a flag value. Note that by providing the ``flag_value`` parameter,
12 unmodified lines
320 @click.option('--lower', 'transformation', flag_value='lower')321 def info(transformation):322 click.echo(getattr(sys.platform, transformation)())323360And on the command line:361324.. click:run::325326 invoke(info, args=['--upper'])365 invoke(info, args=['--lower'])327 invoke(info, args=['--help'])328 invoke(info)329368.. _choice-opts:330370Choice Options371--------------372373Sometimes, you want to have a parameter be a choice of a list of values.374In that case you can use :class:`Choice` type. It can be instantiated375with a list of valid values. The originally passed choice will be returned,376not the str passed on the command line. Token normalization functions and377``case_sensitive=False`` can cause the two to be different but still match.378:meth:`Choice.normalize_choice` for more info.379380Example:381382.. click:example::383384 import enum385386 class HashType(enum.Enum):387 MD5 = 'MD5'388 SHA1 = 'SHA1'389390 @click.command()391 @click.option('--hash-type',392 type=click.Choice(HashType, case_sensitive=False))393 def digest(hash_type: HashType):394 click.echo(hash_type)395396What it looks like:397398.. click:run::399400 invoke(digest, args=['--hash-type=MD5'])401 println()402 invoke(digest, args=['--hash-type=md5'])403 println()404 invoke(digest, args=['--hash-type=foo'])405 println()406 invoke(digest, args=['--help'])407408Since version 8.2.0 any iterable may be passed to :class:`Choice`, here409an ``Enum`` is used which will result in all enum values to be valid410choices.411412Choices work with options that have ``multiple=True``. If a ``default``413value is given with ``multiple=True``, it should be a list or tuple of414valid choices.415416Choices should be unique after normalization, see417:meth:`Choice.normalize_choice` for more info.418419.. versionchanged:: 7.1420 The resulting value from an option will always be one of the421 originally passed choices regardless of ``case_sensitive``.422331.. _option-prompting:332333Prompting334---------
40 unmodified lines
375By default, the user will be prompted for an input if one was not passed376through the command line. To turn this behavior off, see377:ref:`optional-value`.378471472Password Prompts473----------------474475Click also supports hidden prompts and asking for confirmation. This is476useful for password input:477478.. click:example::479480 import codecs481482 @click.command()483 @click.option(484 "--password", prompt=True, hide_input=True,485 confirmation_prompt=True486 )487 def encode(password):488 click.echo(f"encoded: {codecs.encode(password, 'rot13')}")489490.. click:run::491492 invoke(encode, input=['secret', 'secret'])493494Because this combination of parameters is quite common, this can also be495replaced with the :func:`password_option` decorator:496497.. code-block:: python498499 @click.command()500 @click.password_option()501 def encrypt(password):502 click.echo(f"encoded: to {codecs.encode(password, 'rot13')}")503504379Dynamic Defaults for Prompts380----------------------------381382The ``auto_envvar_prefix`` and ``default_map`` options for the context
92 unmodified lines
475476 invoke(hello)477 invoke(hello, args=['--version'])478605606Yes Parameters607--------------608609For dangerous operations, it's very useful to be able to ask a user for610confirmation. This can be done by adding a boolean ``--yes`` flag and611asking for confirmation if the user did not provide it and to fail in a612callback:613614.. click:example::615616 def abort_if_false(ctx, param, value):617 if not value:618 ctx.abort()619620 @click.command()621 @click.option('--yes', is_flag=True, callback=abort_if_false,622 expose_value=False,623 prompt='Are you sure you want to drop the db?')624 def dropdb():625 click.echo('Dropped all tables!')626627And what it looks like on the command line:628629.. click:run::630631 invoke(dropdb, input=['n'])632 invoke(dropdb, args=['--yes'])633634Because this combination of parameters is quite common, this can also be635replaced with the :func:`confirmation_option` decorator:636637.. click:example::638639 @click.command()640 @click.confirmation_option(prompt='Are you sure you want to drop the db?')641 def dropdb():642 click.echo('Dropped all tables!')643644479Values from Environment Variables480---------------------------------481482A very useful feature of Click is the ability to accept parameters from
159 unmodified lines
642643 if __name__ == '__main__':644 log()645812.. _ranges:813814Range Options815-------------816817The :class:`IntRange` type extends the :data:`INT` type to ensure the818value is contained in the given range. The :class:`FloatRange` type does819the same for :data:`FLOAT`.820821If ``min`` or ``max`` is omitted, that side is *unbounded*. Any value in822that direction is accepted. By default, both bounds are *closed*, which823means the boundary value is included in the accepted range. ``min_open``824and ``max_open`` can be used to exclude that boundary from the range.825826If ``clamp`` mode is enabled, a value that is outside the range is set827to the boundary instead of failing. For example, the range ``0, 5``828would return ``5`` for the value ``10``, or ``0`` for the value ``-1``.829When using :class:`FloatRange`, ``clamp`` can only be enabled if both830bounds are *closed* (the default).831832.. click:example::833834 @click.command()835 @click.option("--count", type=click.IntRange(0, 20, clamp=True))836 @click.option("--digit", type=click.IntRange(0, 9))837 def repeat(count, digit):838 click.echo(str(digit) * count)839840.. click:run::841842 invoke(repeat, args=['--count=100', '--digit=5'])843 invoke(repeat, args=['--count=6', '--digit=12'])844845646Callbacks for Validation647------------------------648649.. versionchanged:: 2.0
86 unmodified lines
added:docs/parameter-types.rst+182 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 = '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.
modified:docs/parameters.rst+3 added-84 removed
1 unmodified line
2==========34.. currentmodule:: click56Click supports only two types of parameters for scripts (by design): options and arguments.6Click supports only two principle types of parameters for scripts (by design): options and arguments.78Options9----------------10
13 unmodified lines
24* Can take an arbitrary number of arguments.25* Are not fully documented by the help page since they may be too specific to be automatically documented. For more see :ref:`documenting-arguments`.26* Can be pulled from environment variables but only explicitly named ones. For more see :ref:`environment-variables`.2728On each principle type you can specify :ref:`parameter-types`. Specifying these types helps Click add details to your help pages and help with the handling of those types.2930.. _parameter_names:3132Parameter Names33---------------
19 unmodified lines
5354.. click:run::5556 invoke(multi_echo, ['--times=3', 'index.txt'], prog_name='multi_echo')5556Parameter Types57---------------5859The supported parameter types are:6061``str`` / :data:`click.STRING`:62 The default parameter type which indicates unicode strings.6364``int`` / :data:`click.INT`:65 A parameter that only accepts integers.6667``float`` / :data:`click.FLOAT`:68 A parameter that only accepts floating point values.6970``bool`` / :data:`click.BOOL`:71 A parameter that accepts boolean values. This is automatically used72 for boolean flags. The string values "1", "true", "t", "yes", "y",73 and "on" convert to ``True``. "0", "false", "f", "no", "n", and74 "off" convert to ``False``.7576:data:`click.UUID`:77 A parameter that accepts UUID values. This is not automatically78 guessed but represented as :class:`uuid.UUID`.7980.. autoclass:: File81 :noindex:8283.. autoclass:: Path84 :noindex:8586.. autoclass:: Choice87 :noindex:8889.. autoclass:: IntRange90 :noindex:9192.. autoclass:: FloatRange93 :noindex:9495.. autoclass:: DateTime96 :noindex:9798How to Implement Custom Types99-------------------------------100101To 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.102103The following code implements an integer type that accepts hex and octal104numbers in addition to normal integers, and converts them into regular105integers.106107.. code-block:: python108109 import click110111 class BasedIntParamType(click.ParamType):112 name = "integer"113114 def convert(self, value, param, ctx):115 if isinstance(value, int):116 return value117118 try:119 if value[:2].lower() == "0x":120 return int(value[2:], 16)121 elif value[:1] == "0":122 return int(value, 8)123 return int(value, 10)124 except ValueError:125 self.fail(f"{value!r} is not a valid integer", param, ctx)126127 BASED_INT = BasedIntParamType()128129The :attr:`~ParamType.name` attribute is optional and is used for130documentation. Call :meth:`~ParamType.fail` if conversion fails. The131``param`` and ``ctx`` arguments may be ``None`` in some cases such as132prompts.133134Values from user input or the command line will be strings, but default135values and Python arguments may already be the correct type. The custom136type should check at the top if the value is already valid and pass it137through to support those cases.