Skip to content
Myr

Resolve conflicts from main.

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

authored by Edward G · committed by Edward G · parents e2f2d84, 8fcf9b0 · Browse files · 16 files+650 added−462 removed
This commit

State

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

Diff stats

16 files+650 added−462 removed

  • tests:+113 added−9 removed
  • other:+537 added−453 removed

16 files+650 added−462 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+4 added-2 removed
70 unmodified lines
71 entry-points72 virtualenv73 setuptools74 parameters75 arguments75 parameter-types76 options77 commands-and-groups77 option-decorators78 arguments79 commands80 commands-and-groups81 documentation82 prompts83 complex84 advanced
27 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-306 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.378379Example:380381.. click:example::382383 @click.command()384 @click.option('--hash-type',385 type=click.Choice(['MD5', 'SHA1'], case_sensitive=False))386 def digest(hash_type):387 click.echo(hash_type)388389What it looks like:390391.. click:run::392393 invoke(digest, args=['--hash-type=MD5'])394 println()395 invoke(digest, args=['--hash-type=md5'])396 println()397 invoke(digest, args=['--hash-type=foo'])398 println()399 invoke(digest, args=['--help'])400401Only pass the choices as list or tuple. Other iterables (like402generators) may lead to unexpected results.403404Choices work with options that have ``multiple=True``. If a ``default``405value is given with ``multiple=True``, it should be a list or tuple of406valid choices.407408Choices should be unique after considering the effects of409``case_sensitive`` and any specified token normalization function.410411.. versionchanged:: 7.1412 The resulting value from an option will always be one of the413 originally passed choices regardless of ``case_sensitive``.414331.. _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`.378463464Password Prompts465----------------466467Click also supports hidden prompts and asking for confirmation. This is468useful for password input:469470.. click:example::471472 import codecs473474 @click.command()475 @click.option(476 "--password", prompt=True, hide_input=True,477 confirmation_prompt=True478 )479 def encode(password):480 click.echo(f"encoded: {codecs.encode(password, 'rot13')}")481482.. click:run::483484 invoke(encode, input=['secret', 'secret'])485486Because this combination of parameters is quite common, this can also be487replaced with the :func:`password_option` decorator:488489.. code-block:: python490491 @click.command()492 @click.password_option()493 def encrypt(password):494 click.echo(f"encoded: to {codecs.encode(password, 'rot13')}")495496379Dynamic 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'])478597598Yes Parameters599--------------600601For dangerous operations, it's very useful to be able to ask a user for602confirmation. This can be done by adding a boolean ``--yes`` flag and603asking for confirmation if the user did not provide it and to fail in a604callback:605606.. click:example::607608 def abort_if_false(ctx, param, value):609 if not value:610 ctx.abort()611612 @click.command()613 @click.option('--yes', is_flag=True, callback=abort_if_false,614 expose_value=False,615 prompt='Are you sure you want to drop the db?')616 def dropdb():617 click.echo('Dropped all tables!')618619And what it looks like on the command line:620621.. click:run::622623 invoke(dropdb, input=['n'])624 invoke(dropdb, args=['--yes'])625626Because this combination of parameters is quite common, this can also be627replaced with the :func:`confirmation_option` decorator:628629.. click:example::630631 @click.command()632 @click.confirmation_option(prompt='Are you sure you want to drop the db?')633 def dropdb():634 click.echo('Dropped all tables!')635636479Values 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()645804.. _ranges:805806Range Options807-------------808809The :class:`IntRange` type extends the :data:`INT` type to ensure the810value is contained in the given range. The :class:`FloatRange` type does811the same for :data:`FLOAT`.812813If ``min`` or ``max`` is omitted, that side is *unbounded*. Any value in814that direction is accepted. By default, both bounds are *closed*, which815means the boundary value is included in the accepted range. ``min_open``816and ``max_open`` can be used to exclude that boundary from the range.817818If ``clamp`` mode is enabled, a value that is outside the range is set819to the boundary instead of failing. For example, the range ``0, 5``820would return ``5`` for the value ``10``, or ``0`` for the value ``-1``.821When using :class:`FloatRange`, ``clamp`` can only be enabled if both822bounds are *closed* (the default).823824.. click:example::825826 @click.command()827 @click.option("--count", type=click.IntRange(0, 20, clamp=True))828 @click.option("--digit", type=click.IntRange(0, 9))829 def repeat(count, digit):830 click.echo(str(digit) * count)831832.. click:run::833834 invoke(repeat, args=['--count=100', '--digit=5'])835 invoke(repeat, args=['--count=6', '--digit=12'])836837646Callbacks 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
3 unmodified lines
4==========56.. currentmodule:: click78Click supports only two types of parameters for scripts (by design): options and arguments.8Click supports only two principle types of parameters for scripts (by design): options and arguments.910Options11----------------12
13 unmodified lines
26* Can take an arbitrary number of arguments.27* Are not fully documented by the help page since they may be too specific to be automatically documented. For more see :ref:`documenting-arguments`.28* Can be pulled from environment variables but only explicitly named ones. For more see :ref:`environment-variables`.2930On 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.3132.. _parameter_names:3334Parameter Names35---------------
19 unmodified lines
5556.. click:run::5758 invoke(multi_echo, ['--times=3', 'index.txt'], prog_name='multi_echo')5758Parameter Types59---------------6061The supported parameter types are:6263``str`` / :data:`click.STRING`:64 The default parameter type which indicates unicode strings.6566``int`` / :data:`click.INT`:67 A parameter that only accepts integers.6869``float`` / :data:`click.FLOAT`:70 A parameter that only accepts floating point values.7172``bool`` / :data:`click.BOOL`:73 A parameter that accepts boolean values. This is automatically used74 for boolean flags. The string values "1", "true", "t", "yes", "y",75 and "on" convert to ``True``. "0", "false", "f", "no", "n", and76 "off" convert to ``False``.7778:data:`click.UUID`:79 A parameter that accepts UUID values. This is not automatically80 guessed but represented as :class:`uuid.UUID`.8182.. autoclass:: File83 :noindex:8485.. autoclass:: Path86 :noindex:8788.. autoclass:: Choice89 :noindex:9091.. autoclass:: IntRange92 :noindex:9394.. autoclass:: FloatRange95 :noindex:9697.. autoclass:: DateTime98 :noindex:99100How to Implement Custom Types101-------------------------------102103To 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.104105The following code implements an integer type that accepts hex and octal106numbers in addition to normal integers, and converts them into regular107integers.108109.. code-block:: python110111 import click112113 class BasedIntParamType(click.ParamType):114 name = "integer"115116 def convert(self, value, param, ctx):117 if isinstance(value, int):118 return value119120 try:121 if value[:2].lower() == "0x":122 return int(value[2:], 16)123 elif value[:1] == "0":124 return int(value, 8)125 return int(value, 10)126 except ValueError:127 self.fail(f"{value!r} is not a valid integer", param, ctx)128129 BASED_INT = BasedIntParamType()130131The :attr:`~ParamType.name` attribute is optional and is used for132documentation. Call :meth:`~ParamType.fail` if conversion fails. The133``param`` and ``ctx`` arguments may be ``None`` in some cases such as134prompts.135136Values from user input or the command line will be strings, but default137values and Python arguments may already be the correct type. The custom138type should check at the top if the value is already valid and pass it139through to support those cases.
modified:src/click/core.py+7 added-7 removed
2190 unmodified lines
2191 same as the name for options, but the metavar for arguments.2192 """2193 return self.name # type: ignore21942195 def make_metavar(self) -> str:2195 def make_metavar(self, ctx: Context) -> str:2196 if self.metavar is not None:2197 return self.metavar21982199 metavar = self.type.get_metavar(self)2199 metavar = self.type.get_metavar(param=self, ctx=ctx)22002201 if metavar is None:2202 metavar = self.type.name.upper()2203
570 unmodified lines
2774 if any_slashes:2775 any_prefix_is_slash = True27762777 if not self.is_flag and not self.count:2778 rv += f" {self.make_metavar()}"2778 rv += f" {self.make_metavar(ctx=ctx)}"27792780 return rv27812782 rv = [_write_opts(self.opts)]
272 unmodified lines
3055 if self.metavar is not None:3056 return self.metavar3057 return self.name.upper() # type: ignore30583059 def make_metavar(self) -> str:3059 def make_metavar(self, ctx: Context) -> str:3060 if self.metavar is not None:3061 return self.metavar3062 var = self.type.get_metavar(self)3062 var = self.type.get_metavar(param=self, ctx=ctx)3063 if not var:3064 var = self.name.upper() # type: ignore3065 if self.deprecated:3066 var += "!"
20 unmodified lines
3087 )3088 return name, [arg], []30893090 def get_usage_pieces(self, ctx: Context) -> list[str]:3091 return [self.make_metavar()]3091 return [self.make_metavar(ctx)]30923093 def get_error_hint(self, ctx: Context) -> str:3094 return f"'{self.make_metavar()}'"3094 return f"'{self.make_metavar(ctx)}'"30953096 def add_to_parser(self, parser: _OptionParser, ctx: Context) -> None:3097 parser.add_argument(dest=self.name, nargs=self.nargs, obj=self)3098
23 unmodified lines
modified:src/click/exceptions.py+3 added-1 removed
172 unmodified lines
173 param_type = self.param.param_type_name174175 msg = self.message176 if self.param is not None:177 msg_extra = self.param.type.get_missing_message(self.param)177 msg_extra = self.param.type.get_missing_message(178 param=self.param, ctx=self.ctx179 )180 if msg_extra:181 if msg:182 msg += f". {msg_extra}"183 else:
125 unmodified lines
modified:src/click/types.py+96 added-45 removed
1from __future__ import annotations23import collections.abc as cabc4import enum5import os6import stat7import sys8import typing as t
14 unmodified lines
23 from .core import Context24 from .core import Parameter25 from .shell_completion import CompletionItem2627ParamTypeValue = t.TypeVar("ParamTypeValue")282930class ParamType:31 """Represents the type of a parameter. Validates and converts values32 from the command line or Python into the correct type.33
54 unmodified lines
88 ) -> t.Any:89 if value is not None:90 return self.convert(value, param, ctx)9189 def get_metavar(self, param: Parameter) -> str | None:92 def get_metavar(self, param: Parameter, ctx: Context) -> str | None:93 """Returns the metavar default for this param if it provides one."""9492 def get_missing_message(self, param: Parameter) -> str | None:95 def get_missing_message(self, param: Parameter, ctx: Context | None) -> str | None:96 """Optionally might return extra information about a missing97 parameter.9899 .. versionadded:: 2.0
129 unmodified lines
229 def __repr__(self) -> str:230 return "STRING"231232230class Choice(ParamType):233class Choice(ParamType, t.Generic[ParamTypeValue]):234 """The choice type allows a value to be checked against a fixed set232 of supported values. All of these values have to be strings.235 of supported values.236234 You should only pass a list or tuple of choices. Other iterables235 (like generators) may lead to surprising results.237 You may pass any iterable value which will be converted to a tuple238 and thus will only be iterated once.239237 The resulting value will always be one of the originally passed choices238 regardless of ``case_sensitive`` or any ``ctx.token_normalize_func``239 being specified.240 The resulting value will always be one of the originally passed choices.241 See :meth:`normalize_choice` for more info on the mapping of strings242 to choices. See :ref:`choice-opts` for an example.243241 See :ref:`choice-opts` for an example.242244 :param case_sensitive: Set to false to make choices case245 insensitive. Defaults to true.246247 .. versionchanged:: 8.2.0248 Non-``str`` ``choices`` are now supported. It can additionally be any249 iterable. Before you were not recommended to pass anything but a list or250 tuple.251252 .. versionadded:: 8.2.0253 Choice normalization can be overridden via :meth:`normalize_choice`.254 """255256 name = "choice"257258 def __init__(250 self, choices: cabc.Sequence[str], case_sensitive: bool = True259 self, choices: cabc.Iterable[ParamTypeValue], case_sensitive: bool = True260 ) -> None:252 self.choices = choices261 self.choices: cabc.Sequence[ParamTypeValue] = tuple(choices)262 self.case_sensitive = case_sensitive263264 def to_info_dict(self) -> dict[str, t.Any]:265 info_dict = super().to_info_dict()266 info_dict["choices"] = self.choices267 info_dict["case_sensitive"] = self.case_sensitive268 return info_dict269270 def _normalized_mapping(271 self, ctx: Context | None = None272 ) -> cabc.Mapping[ParamTypeValue, str]:273 """274 Returns mapping where keys are the original choices and the values are275 the normalized values that are accepted via the command line.276277 This is a simple wrapper around :meth:`normalize_choice`, use that278 instead which is supported.279 """280 return {281 choice: self.normalize_choice(282 choice=choice,283 ctx=ctx,284 )285 for choice in self.choices286 }287288 def normalize_choice(self, choice: ParamTypeValue, ctx: Context | None) -> str:289 """290 Normalize a choice value, used to map a passed string to a choice.291 Each choice must have a unique normalized value.292293 By default uses :meth:`Context.token_normalize_func` and if not case294 sensitive, convert it to a casefolded value.295296 .. versionadded:: 8.2.0297 """298 normed_value = choice.name if isinstance(choice, enum.Enum) else str(choice)299300 if ctx is not None and ctx.token_normalize_func is not None:301 normed_value = ctx.token_normalize_func(normed_value)302303 if not self.case_sensitive:304 normed_value = normed_value.casefold()305306 return normed_value307261 def get_metavar(self, param: Parameter) -> str:308 def get_metavar(self, param: Parameter, ctx: Context) -> str | None:309 if param.param_type_name == "option" and not param.show_choices: # type: ignore310 choice_metavars = [311 convert_type(type(choice)).name.upper() for choice in self.choices312 ]313 choices_str = "|".join([*dict.fromkeys(choice_metavars)])314 else:268 choices_str = "|".join([str(i) for i in self.choices])315 choices_str = "|".join(316 [str(i) for i in self._normalized_mapping(ctx=ctx).values()]317 )318319 # Use curly braces to indicate a required argument.320 if param.required and param.param_type_name == "argument":321 return f"{{{choices_str}}}"322323 # Use square braces to indicate an option or optional argument.324 return f"[{choices_str}]"325277 def get_missing_message(self, param: Parameter) -> str:278 return _("Choose from:\n\t{choices}").format(choices=",\n\t".join(self.choices))326 def get_missing_message(self, param: Parameter, ctx: Context | None) -> str:327 """328 Message shown when no choice is passed.329330 .. versionchanged:: 8.2.0 Added ``ctx`` argument.331 """332 return _("Choose from:\n\t{choices}").format(333 choices=",\n\t".join(self._normalized_mapping(ctx=ctx).values())334 )335336 def convert(337 self, value: t.Any, param: Parameter | None, ctx: Context | None282 ) -> t.Any:283 # Match through normalization and case sensitivity284 # first do token_normalize_func, then lowercase285 # preserve original `value` to produce an accurate message in286 # `self.fail`287 normed_value = value288 normed_choices = {choice: choice for choice in self.choices}338 ) -> ParamTypeValue:339 """340 For a given value from the parser, normalize it and find its341 matching normalized value in the list of choices. Then return the342 matched "original" choice.343 """344 normed_value = self.normalize_choice(choice=value, ctx=ctx)345 normalized_mapping = self._normalized_mapping(ctx=ctx)346290 if ctx is not None and ctx.token_normalize_func is not None:291 normed_value = ctx.token_normalize_func(value)292 normed_choices = {293 ctx.token_normalize_func(normed_choice): original294 for normed_choice, original in normed_choices.items()295 }347 try:348 return next(349 original350 for original, normalized in normalized_mapping.items()351 if normalized == normed_value352 )353 except StopIteration:354 self.fail(355 self.get_invalid_choice_message(value=value, ctx=ctx),356 param=param,357 ctx=ctx,358 )359297 if not self.case_sensitive:298 normed_value = normed_value.casefold()299 normed_choices = {300 normed_choice.casefold(): original301 for normed_choice, original in normed_choices.items()302 }303304 if normed_value in normed_choices:305 return normed_choices[normed_value]306307 self.fail(self.get_invalid_choice_message(value), param, ctx)308309 def get_invalid_choice_message(self, value: t.Any) -> str:360 def get_invalid_choice_message(self, value: t.Any, ctx: Context | None) -> str:361 """Get the error message when the given choice is invalid.362363 :param value: The invalid value.364365 .. versionadded:: 8.2366 """316 choices_str = ", ".join(map(repr, self.choices))367 choices_str = ", ".join(map(repr, self._normalized_mapping(ctx=ctx).values()))368 return ngettext(369 "{value!r} is not {choice}.",370 "{value!r} is not one of {choices}.",371 len(self.choices),
60 unmodified lines
432 info_dict = super().to_info_dict()433 info_dict["formats"] = self.formats434 return info_dict435385 def get_metavar(self, param: Parameter) -> str:436 def get_metavar(self, param: Parameter, ctx: Context) -> str | None:437 return f"[{'|'.join(self.formats)}]"438439 def _try_to_convert_date(self, value: t.Any, format: str) -> datetime | None:440 try:
720 unmodified lines
modified:tests/test_basic.py+79 added
1from __future__ import annotations23import enum4import os5from itertools import chain67import pytest
397 unmodified lines
405 result = runner.invoke(cli, ["--help"])406 assert "{foo|bar|baz}" in result.output407408409def test_choice_argument_enum(runner):410 class MyEnum(str, enum.Enum):411 FOO = "foo-value"412 BAR = "bar-value"413 BAZ = "baz-value"414415 @click.command()416 @click.argument("method", type=click.Choice(MyEnum, case_sensitive=False))417 def cli(method: MyEnum):418 assert isinstance(method, MyEnum)419 click.echo(method)420421 result = runner.invoke(cli, ["foo"])422 assert result.output == "foo-value\n"423 assert not result.exception424425 result = runner.invoke(cli, ["meh"])426 assert result.exit_code == 2427 assert (428 "Invalid value for '{foo|bar|baz}': 'meh' is not one of 'foo',"429 " 'bar', 'baz'." in result.output430 )431432 result = runner.invoke(cli, ["--help"])433 assert "{foo|bar|baz}" in result.output434435436def test_choice_argument_custom_type(runner):437 class MyClass:438 def __init__(self, value: str) -> None:439 self.value = value440441 def __str__(self) -> str:442 return self.value443444 @click.command()445 @click.argument(446 "method", type=click.Choice([MyClass("foo"), MyClass("bar"), MyClass("baz")])447 )448 def cli(method: MyClass):449 assert isinstance(method, MyClass)450 click.echo(method)451452 result = runner.invoke(cli, ["foo"])453 assert not result.exception454 assert result.output == "foo\n"455456 result = runner.invoke(cli, ["meh"])457 assert result.exit_code == 2458 assert (459 "Invalid value for '{foo|bar|baz}': 'meh' is not one of 'foo',"460 " 'bar', 'baz'." in result.output461 )462463 result = runner.invoke(cli, ["--help"])464 assert "{foo|bar|baz}" in result.output465466467def test_choice_argument_none(runner):468 @click.command()469 @click.argument(470 "method", type=click.Choice(["not-none", None], case_sensitive=False)471 )472 def cli(method: str | None):473 assert isinstance(method, str) or method is None474 click.echo(method)475476 result = runner.invoke(cli, ["not-none"])477 assert not result.exception478 assert result.output == "not-none\n"479480 # None is not yet supported.481 result = runner.invoke(cli, ["none"])482 assert result.exception483484485def test_datetime_option_default(runner):486 @click.command()487 @click.option("--start_date", type=click.DateTime())488 def cli(start_date):
166 unmodified lines
modified:tests/test_formatting.py+1 added-1 removed
246 unmodified lines
247248249def test_formatting_custom_type_metavar(runner):250 class MyType(click.ParamType):251 def get_metavar(self, param):251 def get_metavar(self, param: click.Parameter, ctx: click.Context):252 return "MY_TYPE"253254 @click.command("foo")255 @click.help_option()
113 unmodified lines
modified:tests/test_info_dict.py+2 added-2 removed
104 unmodified lines
105 id="UNPROCESSED ParamType",106 ),107 pytest.param(*STRING_PARAM_TYPE, id="STRING ParamType"),108 pytest.param(109 click.Choice(["a", "b"]),109 click.Choice(("a", "b")),110 {111 "param_type": "Choice",112 "name": "choice",113 "choices": ["a", "b"],113 "choices": ("a", "b"),114 "case_sensitive": True,115 },116 id="Choice ParamType",117 ),
158 unmodified lines
modified:tests/test_normalization.py+30 added-5 removed
15 unmodified lines
161718def test_choice_normalization(runner):19 @click.command(context_settings=CONTEXT_SETTINGS)20 @click.option("--choice", type=click.Choice(["Foo", "Bar"]))21 def cli(choice):22 click.echo(choice)20 @click.option(21 "--method",22 type=click.Choice(23 ["SCREAMING_SNAKE_CASE", "snake_case", "PascalCase", "kebab-case"],24 case_sensitive=False,25 ),26 )27 def cli(method):28 click.echo(method)2924 result = runner.invoke(cli, ["--CHOICE", "FOO"])25 assert result.output == "Foo\n"30 result = runner.invoke(cli, ["--METHOD=snake_case"])31 assert not result.exception, result.output32 assert result.output == "snake_case\n"3334 # Even though it's case sensitive, the choice's original value is preserved35 result = runner.invoke(cli, ["--method=pascalcase"])36 assert not result.exception, result.output37 assert result.output == "PascalCase\n"3839 result = runner.invoke(cli, ["--method=meh"])40 assert result.exit_code == 241 assert (42 "Invalid value for '--method': 'meh' is not one of "43 "'screaming_snake_case', 'snake_case', 'pascalcase', 'kebab-case'."44 ) in result.output4546 result = runner.invoke(cli, ["--help"])47 assert (48 "--method [screaming_snake_case|snake_case|pascalcase|kebab-case]"49 in result.output50 )515253def test_command_normalization(runner):54 @click.group(context_settings=CONTEXT_SETTINGS)55 def cli():56 pass
7 unmodified lines
modified:tests/test_types.py+1 added-1 removed
246 unmodified lines
247248249def test_choice_get_invalid_choice_message():250 choice = click.Choice(["a", "b", "c"])251 message = choice.get_invalid_choice_message("d")251 message = choice.get_invalid_choice_message("d", ctx=None)252 assert message == "'d' is not one of 'a', 'b', 'c'."
modified:CHANGES.rst+11 added-8 removed
5 unmodified lines
6Unreleased78- Drop support for Python 3.7. :pr:`2588`9- Use modern packaging metadata with ``pyproject.toml`` instead of ``setup.cfg``.10 :pr:`326`11- Use ``flit_core`` instead of ``setuptools`` as build backend.10 :pr:`2438`11- Use ``flit_core`` instead of ``setuptools`` as build backend. :pr:`2543`12- Deprecate the ``__version__`` attribute. Use feature detection, or13 ``importlib.metadata.version("click")``, instead. :issue:`2598`14- ``BaseCommand`` is deprecated. ``Command`` is the base class for all15 commands. :issue:`2589`
24 unmodified lines
40 items used in ``get_help_record`` to render help text. :issue:`2516`41 :pr:`2517`42- Keep stdout and stderr streams independent in ``CliRunner``. Always43 collect stderr output and never raise an exception. Add a new44 output` stream to simulate what the user sees in its terminal. Removes44 output stream to simulate what the user sees in its terminal. Removes45 the ``mix_stderr`` parameter in ``CliRunner``. :issue:`2522` :pr:`2523`46- ``Option.show_envvar`` now also shows environment variable in error messages.47 :issue:`2695` :pr:`2696`48- ``Context.close`` will be called on exit. This results in all49 ``Context.call_on_close`` callbacks and context managers added via50 ``Context.with_resource`` to be closed on exit as well. :pr:`2680`51- Add ``ProgressBar(hidden: bool)`` to allow hiding the progressbar. :issue:`2609`52- A ``UserWarning`` will be shown when multiple parameters attempt to use the53 same name. :issue:`2396``53 same name. :issue:`2396`54- When using ``Option.envvar`` with ``Option.flag_value``, the ``flag_value``55 will always be used instead of the value of the environment variable.56 :issue:`2746` :pr:`2788`57- Add ``Choice.get_invalid_choice_message`` method for customizing the
1 unmodified line
59- If help is shown because ``no_args_is_help`` is enabled (defaults to ``True``60 for groups, ``False`` for commands), the exit code is 2 instead of 0.61 :issue:`1489` :pr:`1489`62- Contexts created during shell completion are closed properly, fixing63 ``ResourceWarning``s when using ``click.File``. :issue:`2644` :pr:`2800`63 a ``ResourceWarning`` when using ``click.File``. :issue:`2644` :pr:`2800`64 :pr:`2767`65- ``click.edit(filename)`` now supports passing an iterable of filenames in66 case the editor supports editing multiple files at once. Its return type67 is now also typed: ``AnyStr`` if ``text`` is passed, otherwise ``None``.
19 unmodified lines
87 ``(Deprecated) help`` to ``help (DEPRECATED)``.88 - Parameters cannot be required nor prompted or an error is raised.89 - A warning will be printed when something deprecated is used.9091- Add a ``catch_exceptions`` parameter to :class:`CliRunner`. If92 ``catch_exceptions`` is not passed to :meth:`CliRunner.invoke`,93 the value from :class:`CliRunner`. :issue:`2817` :pr:`2818`91- Add a ``catch_exceptions`` parameter to ``CliRunner``. If92 ``catch_exceptions`` is not passed to ``CliRunner.invoke``,93 the value from ``CliRunner``. :issue:`2817` :pr:`2818`94- ``Option.flag_value`` will no longer have a default value set based on95 ``Option.default`` if ``Option.is_flag`` is ``False``. This results in96 ``Option.default`` not needing to implement `__bool__`. :pr:`2829`97- Incorrect ``click.edit`` typing has been corrected. :pr:`2804`98- ``Choice`` is now generic and supports any iterable value.99 This allows you to use enums and other non-``str`` values. :pr:`2796`100 :issue:`605`101102Version 8.1.8103-------------104
1117 unmodified lines