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
Provenance
- Commit
b72256a- Tree
286f845- Author
Edward G <edward.g2013@gmail.com>- Committer
Edward G <edward.g2013@gmail.com>- Parent 1
e2f2d84- Parent 2
8fcf9b0
16 files changed+650 added−462 removed
modified:docs/api.rst+1 added
111 unmodified lines112 .. autoclass:: click.core.ParameterSource113 :members:114 :member-order: bysource115 116+.. _click-api-types:117 118 Types119 -----120 91 unmodified linesmodified:docs/documentation.rst+36 added
106 unmodified lines107 .. click:run::108 109 invoke(touch, args=['--help'])110 111+112+Showing Defaults113+---------------------------114+To control the appearance of defaults pass ``show_default``.115+116+.. click:example::117+118+ @click.command()119+ @click.option('--n', default=1, show_default=False, help='number of dots')120+ def dots(n):121+ click.echo('.' * n)122+123+.. click:run::124+125+ invoke(dots, args=['--help'])126+127+For single option boolean flags, the default remains hidden if the default value is False even if show default is true.128+129+.. click:example::130+131+ @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)141+142+.. click:run::143+144+ invoke(dots, args=['--help'])145+146+147 Click's Wrapping Behavior148 ----------------------------149 Click'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 linesmodified:docs/index.rst+4 added-2 removed
70 unmodified lines71 entry-points72 virtualenv73 setuptools74 parameters75- arguments75+ parameter-types76 options77- commands-and-groups77+ option-decorators78+ arguments79 commands80+ commands-and-groups81 documentation82 prompts83 complex84 advanced27 unmodified linesadded:docs/option-decorators.rst+80 added
1+Options Shortcut Decorators2+===========================3+4+.. currentmodule:: click5+6+For convenience commonly used combinations of options arguments are available as their own decorators.7+8+.. contents::9+ :depth: 210+ :local:11+12+Password Option13+------------------14+15+Click supports hidden prompts and asking for confirmation. This is16+useful for password input:17+18+.. click:example::19+20+ import codecs21+22+ @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')}")29+30+.. click:run::31+32+ invoke(encode, input=['secret', 'secret'])33+34+Because this combination of parameters is quite common, this can also be35+replaced with the :func:`password_option` decorator:36+37+.. code-block:: python38+39+ @click.command()40+ @click.password_option()41+ def encrypt(password):42+ click.echo(f"encoded: to {codecs.encode(password, 'rot13')}")43+44+Confirmation Option45+--------------------46+47+For dangerous operations, it's very useful to be able to ask a user for48+confirmation. This can be done by adding a boolean ``--yes`` flag and49+asking for confirmation if the user did not provide it and to fail in a50+callback:51+52+.. click:example::53+54+ def abort_if_false(ctx, param, value):55+ if not value:56+ ctx.abort()57+58+ @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!')64+65+And what it looks like on the command line:66+67+.. click:run::68+69+ invoke(dropdb, input=['n'])70+ invoke(dropdb, args=['--yes'])71+72+Because this combination of parameters is quite common, this can also be73+replaced with the :func:`confirmation_option` decorator:74+75+.. click:example::76+77+ @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:2 3 Options4-=======4+=========5 6 .. currentmodule:: click7 8-Adding options to commands can be accomplished by the :func:`option`9-decorator. Since options can come in various different versions, there10-are a ton of parameters to configure their behavior. Options in click are11-distinct from :ref:`positional arguments <arguments>`.8+Adding options to commands can be accomplished with the :func:`option`9+decorator. Options in Click are distinct from :ref:`positional arguments <arguments>`.10 13-Name Your Options14------------------11+Useful and often used kwargs are:12 16-Options have a name that will be used as the Python argument name when17-calling the decorated function. This can be inferred from the option18-names or given explicitly. Names are given as position arguments to the19-decorator.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`18 21-A name is chosen in the following order19+.. contents::20+ :depth: 221+ :local:22 23-1. 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.25-2. If there is at least one name prefixed with two dashes, the first26- one given is used as the name.27-3. The first name prefixed with one dash is used otherwise.23+Option Decorator24+-----------------25+Click expects you to pass at least two positional arguments to the option decorator. They are option name and function argument name.26 29-To get the Python argument name, the chosen name is converted to lower30-case, up to two dashes are removed as the prefix, and other dashes are31-converted to underscores.27+.. click:example::28 33-.. code-block:: python34-29 @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)33 40-.. code-block:: python34+.. click:run::35 42- @click.command()43- @click.option('-s', '--string-to-echo', 'string')44- def echo(string):45- click.echo(string)36+ invoke(echo, args=['--help'])37 47-- ``"-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``38+However, 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.39 55-Basic Value Options56--------------------57-58-The most basic option is a value option. These options accept one59-argument which is a value. If no type is provided, the type of the default60-value 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 the62-parameter is the first long option defined; otherwise the first short one is63-used. By default, options are not required, however to make an option required,64-simply pass in `required=True` as an argument to the decorator.65-40 .. click:example::41 42 @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)46 73-.. click:example::47+.. click:run::48 75- # 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!'])50 81-.. click:example::51+More formally, Click will try to infer the function argument name by:52 83- # 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}")53+1. If a positional argument name does not have a prefix, it is chosen.54+2. If a positional argument name starts with with two dashes, the first one given is chosen.55+3. The first positional argument prefixed with one dash is chosen otherwise.56 90-And on the command line:57+The 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.58 92-.. click:run::59+.. list-table:: Examples60+ :widths: 15 1061+ :header-rows: 162 94- 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+ - _f79 96-In this case the option is of type :data:`INT` because the default value97-is an integer.80+Basic Example81+---------------82+A 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``.83 99-To show the default values when showing command help, use ``show_default=True``100-84 .. click:example::85 86 @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)90 91+92 .. click:run::93 110- invoke(dots, args=['--help'])94+ invoke(print_this, args=['--text=this'])95 112-For single option boolean flags, the default remains hidden if the default113-value is False.96+ invoke(print_this, args=[])97 98+.. click:run::99+100+ invoke(print_this, args=['--help'])101+102+103+Setting a Default104+---------------------------105+Instead of setting the ``type``, you may set a default and Click will try to infer the type.106+107 .. click:example::108 109 @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)113 114 .. click:run::115 130- invoke(dots, args=['--help'])116+ invoke(dots, args=['--help'])117 132-118 Multi Value Options119 -------------------120 136-Sometimes, you have options that take more than one argument. For options,137-only a fixed number of arguments is supported. This can be configured by138-the ``nargs`` parameter. The values are then stored as a tuple.121+To 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.122 123 .. click:example::124 125 @click.command()1 unmodified line127 def findme(pos):128 a, b = pos129 click.echo(f"{a} / {b}")130 148-And on the command line:149-131 .. click:run::132 133 invoke(findme, args=['--pos', '2.0', '3.0'])134 135+136 .. _tuple-type:137 156-Tuples as Multi Value Options138+Multi Value Options as Tuples139 -----------------------------140 141 .. versionadded:: 4.0142 30 unmodified lines173 174 .. _multiple-options:175 176 Multiple Options195-----------------177+-----------------178 197-Similarly to ``nargs``, there is also the case of wanting to support a198-parameter being provided multiple times and have all the values recorded --199-not just the last one. For instance, ``git commit -m foo -m bar`` would200-record two lines for the commit message: ``foo`` and ``bar``. This can be201-accomplished with the ``multiple`` flag:179+The 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.180 203-Example:204-181 .. click:example::182 183 @click.command()184 @click.option('--message', '-m', multiple=True)185 def commit(message):186 click.echo('\n'.join(message))187 212-And on the command line:213-188 .. click:run::189 216- invoke(commit, args=['-m', 'foo', '-m', 'bar'])190+ invoke(commit, args=['-m', 'foo', '-m', 'bar', '-m', 'here'])191 218-When passing a ``default`` with ``multiple=True``, the default value219-must be a list or tuple, otherwise it will be interpreted as a list of220-single characters.221-222-.. code-block:: python223-224- @click.option("--format", multiple=True, default=["json"])225-226-192 Counting193 --------194+To 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.195 230-In some very rare circumstances, it is interesting to use the repetition231-of options to count an integer up. This can be used for verbosity flags,232-for instance:233-196 .. click:example::197 198 @click.command()199 @click.option('-v', '--verbose', count=True)200 def log(verbose):201 click.echo(f"Verbosity: {verbose}")202 241-And on the command line:242-203 .. click:run::204 205+ invoke(log, args=[])206 invoke(log, args=['-vvv'])207 247-Boolean Flags248--------------208+Boolean209+------------------------210 250-Boolean flags are options that can be enabled or disabled. This can be251-accomplished by defining two flags in one go separated by a slash (``/``)252-for enabling or disabling the option. (If a slash is in an option string,253-Click automatically knows that it's a boolean flag and will pass254-``is_flag=True`` implicitly.) Click always wants you to provide an enable255-and disable flag so that you can change the default later.211+Boolean 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.212 257-Example:258-213 .. click:example::214 215 import sys216 217 @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)224 271-And on the command line:225 226 .. click:run::227 275- invoke(info, args=['--shout'])276- invoke(info, args=['--no-shout'])228 invoke(info)229+ invoke(info, args=['--shout'])230 279-If you really don't want an off-switch, you can just define one and280-manually inform Click that something is a flag:231 232+To implement this more explicitly, pass in on-option ``/`` off-option. Click will automatically set ``is_flag=True``. Click always wants you to provide an enable233+and disable flag so that you can change the default later.234+235 .. click:example::236 237 import sys238 239 @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)246 294-And on the command line:295-247 .. click:run::248 298- invoke(info, args=['--shout'])249 invoke(info)250+ invoke(info, args=['--shout'])251+ invoke(info, args=['--no-shout'])252 301-Note that if a slash is contained in your option already (for instance, if302-you use Windows-style parameters where ``/`` is the prefix character), you303-can alternatively split the parameters through ``;`` instead:253+If 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.254 255 .. click:example::256 257 @click.command()258 @click.option('/debug;/no-debug')259 def log(debug):260 click.echo(f"debug={debug}")261 312- if __name__ == '__main__':313- log()314-262 .. versionchanged:: 6.0263 317-If you want to define an alias for the second option only, then you will318-need to use leading whitespace to disambiguate the format string:264+If you want to define an alias for the second option only, then you will need to use leading whitespace to disambiguate the format string.265 320-Example:321-266 .. click:example::267 268 import sys269 270 @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 lines278 .. click:run::279 280 invoke(info, args=['--help'])281 282+Flag Value283+---------------284+To 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:285+286+.. click:example::287+288+ import sys289+290+ @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)())295+296+.. click:run::297+298+ invoke(info, args=['--help'])299+ invoke(info, args=['--upper'])300+ invoke(info, args=['--lower'])301+302 Feature Switches339-----------------303+---------------------------304 305 In addition to boolean flags, there are also feature switches. These are306 implemented by setting multiple options to the same parameter name and307 defining a flag value. Note that by providing the ``flag_value`` parameter,12 unmodified lines320 @click.option('--lower', 'transformation', flag_value='lower')321 def info(transformation):322 click.echo(getattr(sys.platform, transformation)())323 360-And on the command line:361-324 .. click:run::325 326 invoke(info, args=['--upper'])365- invoke(info, args=['--lower'])327+ invoke(info, args=['--help'])328 invoke(info)329 368-.. _choice-opts:330 370-Choice Options371---------------372-373-Sometimes, you want to have a parameter be a choice of a list of values.374-In that case you can use :class:`Choice` type. It can be instantiated375-with a list of valid values. The originally passed choice will be returned,376-not 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-379-Example:380-381-.. click:example::382-383- @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)388-389-What it looks like:390-391-.. click:run::392-393- 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'])400-401-Only pass the choices as list or tuple. Other iterables (like402-generators) may lead to unexpected results.403-404-Choices work with options that have ``multiple=True``. If a ``default``405-value is given with ``multiple=True``, it should be a list or tuple of406-valid choices.407-408-Choices should be unique after considering the effects of409-``case_sensitive`` and any specified token normalization function.410-411-.. versionchanged:: 7.1412- The resulting value from an option will always be one of the413- originally passed choices regardless of ``case_sensitive``.414-331 .. _option-prompting:332 333 Prompting334 ---------40 unmodified lines375 By default, the user will be prompted for an input if one was not passed376 through the command line. To turn this behavior off, see377 :ref:`optional-value`.378 463-464-Password Prompts465-----------------466-467-Click also supports hidden prompts and asking for confirmation. This is468-useful for password input:469-470-.. click:example::471-472- import codecs473-474- @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')}")481-482-.. click:run::483-484- invoke(encode, input=['secret', 'secret'])485-486-Because this combination of parameters is quite common, this can also be487-replaced with the :func:`password_option` decorator:488-489-.. code-block:: python490-491- @click.command()492- @click.password_option()493- def encrypt(password):494- click.echo(f"encoded: to {codecs.encode(password, 'rot13')}")495-496-379 Dynamic Defaults for Prompts380 ----------------------------381 382 The ``auto_envvar_prefix`` and ``default_map`` options for the context92 unmodified lines475 476 invoke(hello)477 invoke(hello, args=['--version'])478 597-598-Yes Parameters599---------------600-601-For dangerous operations, it's very useful to be able to ask a user for602-confirmation. This can be done by adding a boolean ``--yes`` flag and603-asking for confirmation if the user did not provide it and to fail in a604-callback:605-606-.. click:example::607-608- def abort_if_false(ctx, param, value):609- if not value:610- ctx.abort()611-612- @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!')618-619-And what it looks like on the command line:620-621-.. click:run::622-623- invoke(dropdb, input=['n'])624- invoke(dropdb, args=['--yes'])625-626-Because this combination of parameters is quite common, this can also be627-replaced with the :func:`confirmation_option` decorator:628-629-.. click:example::630-631- @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!')635-636-479 Values from Environment Variables480 ---------------------------------481 482 A very useful feature of Click is the ability to accept parameters from159 unmodified lines642 643 if __name__ == '__main__':644 log()645 804-.. _ranges:805-806-Range Options807--------------808-809-The :class:`IntRange` type extends the :data:`INT` type to ensure the810-value is contained in the given range. The :class:`FloatRange` type does811-the same for :data:`FLOAT`.812-813-If ``min`` or ``max`` is omitted, that side is *unbounded*. Any value in814-that direction is accepted. By default, both bounds are *closed*, which815-means the boundary value is included in the accepted range. ``min_open``816-and ``max_open`` can be used to exclude that boundary from the range.817-818-If ``clamp`` mode is enabled, a value that is outside the range is set819-to the boundary instead of failing. For example, the range ``0, 5``820-would return ``5`` for the value ``10``, or ``0`` for the value ``-1``.821-When using :class:`FloatRange`, ``clamp`` can only be enabled if both822-bounds are *closed* (the default).823-824-.. click:example::825-826- @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)831-832-.. click:run::833-834- invoke(repeat, args=['--count=100', '--digit=5'])835- invoke(repeat, args=['--count=6', '--digit=12'])836-837-646 Callbacks for Validation647 ------------------------648 649 .. versionchanged:: 2.086 unmodified linesadded:docs/parameter-types.rst+182 added
1+.. _parameter-types:2+3+Parameter Types4+==================5+6+.. currentmodule:: click7+8+When the parameter type is set using ``type``, Click will leverage the type to make your life easier, for example adding data to your help pages. Most examples are done with options, but types are available to options and arguments.9+10+.. contents::11+ :depth: 212+ :local:13+14+Built-in Types Examples15+------------------------16+17+.. _choice-opts:18+19+Choice20+^^^^^^^^^^^^^^^^^^^^^^21+22+Sometimes, you want to have a parameter be a choice of a list of values.23+In that case you can use :class:`Choice` type. It can be instantiated24+with a list of valid values. The originally passed choice will be returned,25+not the str passed on the command line. Token normalization functions and26+``case_sensitive=False`` can cause the two to be different but still match.27+:meth:`Choice.normalize_choice` for more info.28+29+Example:30+31+.. click:example::32+33+ import enum34+35+ class HashType(enum.Enum):36+ MD5 = 'MD5'37+ SHA1 = 'SHA1'38+39+ @click.command()40+ @click.option('--hash-type',41+ type=click.Choice(HashType, case_sensitive=False))42+ def digest(hash_type: HashType):43+ click.echo(hash_type)44+45+What it looks like:46+47+.. click:run::48+49+ invoke(digest, args=['--hash-type=MD5'])50+ println()51+ invoke(digest, args=['--hash-type=md5'])52+ println()53+ invoke(digest, args=['--hash-type=foo'])54+ println()55+ invoke(digest, args=['--help'])56+57+Since version 8.2.0 any iterable may be passed to :class:`Choice`, here58+an ``Enum`` is used which will result in all enum values to be valid59+choices.60+61+Choices work with options that have ``multiple=True``. If a ``default``62+value is given with ``multiple=True``, it should be a list or tuple of63+valid choices.64+65+Choices should be unique after normalization, see66+:meth:`Choice.normalize_choice` for more info.67+68+.. versionchanged:: 7.169+ The resulting value from an option will always be one of the70+ originally passed choices regardless of ``case_sensitive``.71+72+.. _ranges:73+74+Int and Float Ranges75+^^^^^^^^^^^^^^^^^^^^^^^76+77+The :class:`IntRange` type extends the :data:`INT` type to ensure the78+value is contained in the given range. The :class:`FloatRange` type does79+the same for :data:`FLOAT`.80+81+If ``min`` or ``max`` is omitted, that side is *unbounded*. Any value in82+that direction is accepted. By default, both bounds are *closed*, which83+means the boundary value is included in the accepted range. ``min_open``84+and ``max_open`` can be used to exclude that boundary from the range.85+86+If ``clamp`` mode is enabled, a value that is outside the range is set87+to the boundary instead of failing. For example, the range ``0, 5``88+would return ``5`` for the value ``10``, or ``0`` for the value ``-1``.89+When using :class:`FloatRange`, ``clamp`` can only be enabled if both90+bounds are *closed* (the default).91+92+.. click:example::93+94+ @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)99+100+.. click:run::101+102+ invoke(repeat, args=['--count=100', '--digit=5'])103+ invoke(repeat, args=['--count=6', '--digit=12'])104+105+106+Built-in Types Listing107+-----------------------108+The supported parameter :ref:`click-api-types` are:109+110+* ``str`` / :data:`click.STRING`: The default parameter type which indicates unicode strings.111+112+* ``int`` / :data:`click.INT`: A parameter that only accepts integers.113+114+* ``float`` / :data:`click.FLOAT`: A parameter that only accepts floating point values.115+116+* ``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``.120+121+* :data:`click.UUID`:122+ A parameter that accepts UUID values. This is not automatically123+ guessed but represented as :class:`uuid.UUID`.124+125+* .. autoclass:: Choice126+ :noindex:127+128+* .. autoclass:: DateTime129+ :noindex:130+131+* .. autoclass:: File132+ :noindex:133+134+* .. autoclass:: FloatRange135+ :noindex:136+137+* .. autoclass:: IntRange138+ :noindex:139+140+* .. autoclass:: Path141+ :noindex:142+143+How to Implement Custom Types144+-------------------------------145+146+To implement a custom type, you need to subclass the :class:`ParamType` class. For simple cases, passing a Python function that fails with a `ValueError` is also supported, though discouraged. Override the :meth:`~ParamType.convert` method to convert the value from a string to the correct type.147+148+The following code implements an integer type that accepts hex and octal149+numbers in addition to normal integers, and converts them into regular150+integers.151+152+.. code-block:: python153+154+ import click155+156+ class BasedIntParamType(click.ParamType):157+ name = "integer"158+159+ def convert(self, value, param, ctx):160+ if isinstance(value, int):161+ return value162+163+ 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)171+172+ BASED_INT = BasedIntParamType()173+174+The :attr:`~ParamType.name` attribute is optional and is used for175+documentation. Call :meth:`~ParamType.fail` if conversion fails. The176+``param`` and ``ctx`` arguments may be ``None`` in some cases such as177+prompts.178+179+Values from user input or the command line will be strings, but default180+values and Python arguments may already be the correct type. The custom181+type should check at the top if the value is already valid and pass it182+through to support those cases.modified:docs/parameters.rst+3 added-84 removed
3 unmodified lines4 ==========5 6 .. currentmodule:: click7 8-Click supports only two types of parameters for scripts (by design): options and arguments.8+Click supports only two principle types of parameters for scripts (by design): options and arguments.9 10 Options11 ----------------12 13 unmodified lines26 * 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`.29 30+On 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.31+32 .. _parameter_names:33 34 Parameter Names35 ---------------19 unmodified lines55 56 .. click:run::57 58 invoke(multi_echo, ['--times=3', 'index.txt'], prog_name='multi_echo')57-58-Parameter Types59----------------60-61-The supported parameter types are:62-63-``str`` / :data:`click.STRING`:64- The default parameter type which indicates unicode strings.65-66-``int`` / :data:`click.INT`:67- A parameter that only accepts integers.68-69-``float`` / :data:`click.FLOAT`:70- A parameter that only accepts floating point values.71-72-``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``.77-78-:data:`click.UUID`:79- A parameter that accepts UUID values. This is not automatically80- guessed but represented as :class:`uuid.UUID`.81-82-.. autoclass:: File83- :noindex:84-85-.. autoclass:: Path86- :noindex:87-88-.. autoclass:: Choice89- :noindex:90-91-.. autoclass:: IntRange92- :noindex:93-94-.. autoclass:: FloatRange95- :noindex:96-97-.. autoclass:: DateTime98- :noindex:99-100-How to Implement Custom Types101--------------------------------102-103-To implement a custom type, you need to subclass the :class:`ParamType` class. For simple cases, passing a Python function that fails with a `ValueError` is also supported, though discouraged. Override the :meth:`~ParamType.convert` method to convert the value from a string to the correct type.104-105-The following code implements an integer type that accepts hex and octal106-numbers in addition to normal integers, and converts them into regular107-integers.108-109-.. code-block:: python110-111- import click112-113- class BasedIntParamType(click.ParamType):114- name = "integer"115-116- def convert(self, value, param, ctx):117- if isinstance(value, int):118- return value119-120- 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)128-129- BASED_INT = BasedIntParamType()130-131-The :attr:`~ParamType.name` attribute is optional and is used for132-documentation. Call :meth:`~ParamType.fail` if conversion fails. The133-``param`` and ``ctx`` arguments may be ``None`` in some cases such as134-prompts.135-136-Values from user input or the command line will be strings, but default137-values and Python arguments may already be the correct type. The custom138-type should check at the top if the value is already valid and pass it139-through to support those cases.modified:src/click/core.py+7 added-7 removed
2190 unmodified lines2191 same as the name for options, but the metavar for arguments.2192 """2193 return self.name # type: ignore2194 2195- def make_metavar(self) -> str:2195+ def make_metavar(self, ctx: Context) -> str:2196 if self.metavar is not None:2197 return self.metavar2198 2199- metavar = self.type.get_metavar(self)2199+ metavar = self.type.get_metavar(param=self, ctx=ctx)2200 2201 if metavar is None:2202 metavar = self.type.name.upper()2203 570 unmodified lines2774 if any_slashes:2775 any_prefix_is_slash = True2776 2777 if not self.is_flag and not self.count:2778- rv += f" {self.make_metavar()}"2778+ rv += f" {self.make_metavar(ctx=ctx)}"2779 2780 return rv2781 2782 rv = [_write_opts(self.opts)]272 unmodified lines3055 if self.metavar is not None:3056 return self.metavar3057 return self.name.upper() # type: ignore3058 3059- 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 lines3087 )3088 return name, [arg], []3089 3090 def get_usage_pieces(self, ctx: Context) -> list[str]:3091- return [self.make_metavar()]3091+ return [self.make_metavar(ctx)]3092 3093 def get_error_hint(self, ctx: Context) -> str:3094- return f"'{self.make_metavar()}'"3094+ return f"'{self.make_metavar(ctx)}'"3095 3096 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 linesmodified:src/click/exceptions.py+3 added-1 removed
172 unmodified lines173 param_type = self.param.param_type_name174 175 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 linesmodified:src/click/types.py+96 added-45 removed
1 from __future__ import annotations2 3 import collections.abc as cabc4+import enum5 import os6 import stat7 import sys8 import typing as t14 unmodified lines23 from .core import Context24 from .core import Parameter25 from .shell_completion import CompletionItem26 27+ParamTypeValue = t.TypeVar("ParamTypeValue")28 29+30 class 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 lines88 ) -> t.Any:89 if value is not None:90 return self.convert(value, param, ctx)91 89- 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."""94 92- 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.98 99 .. versionadded:: 2.0129 unmodified lines229 def __repr__(self) -> str:230 return "STRING"231 232 230-class Choice(ParamType):233+class 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.236 234- 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.239 237- 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.243 241- See :ref:`choice-opts` for an example.242-244 :param case_sensitive: Set to false to make choices case245 insensitive. Defaults to true.246+247+ .. 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.251+252+ .. versionadded:: 8.2.0253+ Choice normalization can be overridden via :meth:`normalize_choice`.254 """255 256 name = "choice"257 258 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_sensitive263 264 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_dict269 270+ 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.276+277+ 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+ }287+288+ 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.292+293+ By default uses :meth:`Context.token_normalize_func` and if not case294+ sensitive, convert it to a casefolded value.295+296+ .. versionadded:: 8.2.0297+ """298+ normed_value = choice.name if isinstance(choice, enum.Enum) else str(choice)299+300+ if ctx is not None and ctx.token_normalize_func is not None:301+ normed_value = ctx.token_normalize_func(normed_value)302+303+ if not self.case_sensitive:304+ normed_value = normed_value.casefold()305+306+ return normed_value307+261- 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+ )318 319 # Use curly braces to indicate a required argument.320 if param.required and param.param_type_name == "argument":321 return f"{{{choices_str}}}"322 323 # Use square braces to indicate an option or optional argument.324 return f"[{choices_str}]"325 277- 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.329 330+ .. 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+ )335+336 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)346 290- 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+ )359 297- 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- }303-304- if normed_value in normed_choices:305- return normed_choices[normed_value]306-307- self.fail(self.get_invalid_choice_message(value), param, ctx)308-309- 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.362 363 :param value: The invalid value.364 365 .. 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 lines432 info_dict = super().to_info_dict()433 info_dict["formats"] = self.formats434 return info_dict435 385- def get_metavar(self, param: Parameter) -> str:436+ def get_metavar(self, param: Parameter, ctx: Context) -> str | None:437 return f"[{'|'.join(self.formats)}]"438 439 def _try_to_convert_date(self, value: t.Any, format: str) -> datetime | None:440 try:720 unmodified linesmodified:tests/test_basic.py+79 added
1+from __future__ import annotations2+3+import enum4 import os5 from itertools import chain6 7 import pytest397 unmodified lines405 result = runner.invoke(cli, ["--help"])406 assert "{foo|bar|baz}" in result.output407 408 409+def test_choice_argument_enum(runner):410+ class MyEnum(str, enum.Enum):411+ FOO = "foo-value"412+ BAR = "bar-value"413+ BAZ = "baz-value"414+415+ @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)420+421+ result = runner.invoke(cli, ["foo"])422+ assert result.output == "foo-value\n"423+ assert not result.exception424+425+ 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+ )431+432+ result = runner.invoke(cli, ["--help"])433+ assert "{foo|bar|baz}" in result.output434+435+436+def test_choice_argument_custom_type(runner):437+ class MyClass:438+ def __init__(self, value: str) -> None:439+ self.value = value440+441+ def __str__(self) -> str:442+ return self.value443+444+ @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)451+452+ result = runner.invoke(cli, ["foo"])453+ assert not result.exception454+ assert result.output == "foo\n"455+456+ 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+ )462+463+ result = runner.invoke(cli, ["--help"])464+ assert "{foo|bar|baz}" in result.output465+466+467+def 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)475+476+ result = runner.invoke(cli, ["not-none"])477+ assert not result.exception478+ assert result.output == "not-none\n"479+480+ # None is not yet supported.481+ result = runner.invoke(cli, ["none"])482+ assert result.exception483+484+485 def test_datetime_option_default(runner):486 @click.command()487 @click.option("--start_date", type=click.DateTime())488 def cli(start_date):166 unmodified linesmodified:tests/test_formatting.py+1 added-1 removed
246 unmodified lines247 248 249 def 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"253 254 @click.command("foo")255 @click.help_option()113 unmodified linesmodified:tests/test_info_dict.py+2 added-2 removed
104 unmodified lines105 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 linesmodified:tests/test_normalization.py+30 added-5 removed
15 unmodified lines16 17 18 def 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)29 24- 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"33 34+ # 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"38 39+ 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.output45+46+ result = runner.invoke(cli, ["--help"])47+ assert (48+ "--method [screaming_snake_case|snake_case|pascalcase|kebab-case]"49+ in result.output50+ )51+52+53 def test_command_normalization(runner):54 @click.group(context_settings=CONTEXT_SETTINGS)55 def cli():56 pass7 unmodified linesmodified:tests/test_types.py+1 added-1 removed
246 unmodified lines247 248 249 def 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 lines6 Unreleased7 8 - 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 lines40 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 the1 unmodified line59 - 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 lines87 ``(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.90 91-- 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`101 102 Version 8.1.8103 -------------104 1117 unmodified lines