Rewrite first half of options docs (#2825)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Rowlando13 · committed by GitHub · parent 4ece17a · Browse files · 7 files·+419 added−399 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Trailers
- Co-authored-by: Andreas Backx <andreas@backx.org>
Diff stats
7 files+419 added−399 removed
- other:+419 added−399 removed
Provenance
- Commit
82089af- Tree
f410939- Author
Rowlando13 <67291205+Rowlando13@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent
4ece17a
7 files changed+419 added−399 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+3 added-1 removed
70 unmodified lines71 entry-points72 virtualenv73 setuptools74 parameters75- arguments75+ parameter-types76 options77+ option-decorators78+ arguments79 commands80 documentation81 prompts82 complex28 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-314 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-:meth:`Choice.normalize_choice` for more info.379-380-Example:381-382-.. click:example::383-384- import enum385-386- class HashType(enum.Enum):387- MD5 = 'MD5'388- SHA1 = 'SHA1'389-390- @click.command()391- @click.option('--hash-type',392- type=click.Choice(HashType, case_sensitive=False))393- def digest(hash_type: HashType):394- click.echo(hash_type)395-396-What it looks like:397-398-.. click:run::399-400- invoke(digest, args=['--hash-type=MD5'])401- println()402- invoke(digest, args=['--hash-type=md5'])403- println()404- invoke(digest, args=['--hash-type=foo'])405- println()406- invoke(digest, args=['--help'])407-408-Since version 8.2.0 any iterable may be passed to :class:`Choice`, here409-an ``Enum`` is used which will result in all enum values to be valid410-choices.411-412-Choices work with options that have ``multiple=True``. If a ``default``413-value is given with ``multiple=True``, it should be a list or tuple of414-valid choices.415-416-Choices should be unique after normalization, see417-:meth:`Choice.normalize_choice` for more info.418-419-.. versionchanged:: 7.1420- The resulting value from an option will always be one of the421- originally passed choices regardless of ``case_sensitive``.422-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 471-472-Password Prompts473-----------------474-475-Click also supports hidden prompts and asking for confirmation. This is476-useful for password input:477-478-.. click:example::479-480- import codecs481-482- @click.command()483- @click.option(484- "--password", prompt=True, hide_input=True,485- confirmation_prompt=True486- )487- def encode(password):488- click.echo(f"encoded: {codecs.encode(password, 'rot13')}")489-490-.. click:run::491-492- invoke(encode, input=['secret', 'secret'])493-494-Because this combination of parameters is quite common, this can also be495-replaced with the :func:`password_option` decorator:496-497-.. code-block:: python498-499- @click.command()500- @click.password_option()501- def encrypt(password):502- click.echo(f"encoded: to {codecs.encode(password, 'rot13')}")503-504-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 605-606-Yes Parameters607---------------608-609-For dangerous operations, it's very useful to be able to ask a user for610-confirmation. This can be done by adding a boolean ``--yes`` flag and611-asking for confirmation if the user did not provide it and to fail in a612-callback:613-614-.. click:example::615-616- def abort_if_false(ctx, param, value):617- if not value:618- ctx.abort()619-620- @click.command()621- @click.option('--yes', is_flag=True, callback=abort_if_false,622- expose_value=False,623- prompt='Are you sure you want to drop the db?')624- def dropdb():625- click.echo('Dropped all tables!')626-627-And what it looks like on the command line:628-629-.. click:run::630-631- invoke(dropdb, input=['n'])632- invoke(dropdb, args=['--yes'])633-634-Because this combination of parameters is quite common, this can also be635-replaced with the :func:`confirmation_option` decorator:636-637-.. click:example::638-639- @click.command()640- @click.confirmation_option(prompt='Are you sure you want to drop the db?')641- def dropdb():642- click.echo('Dropped all tables!')643-644-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 812-.. _ranges:813-814-Range Options815--------------816-817-The :class:`IntRange` type extends the :data:`INT` type to ensure the818-value is contained in the given range. The :class:`FloatRange` type does819-the same for :data:`FLOAT`.820-821-If ``min`` or ``max`` is omitted, that side is *unbounded*. Any value in822-that direction is accepted. By default, both bounds are *closed*, which823-means the boundary value is included in the accepted range. ``min_open``824-and ``max_open`` can be used to exclude that boundary from the range.825-826-If ``clamp`` mode is enabled, a value that is outside the range is set827-to the boundary instead of failing. For example, the range ``0, 5``828-would return ``5`` for the value ``10``, or ``0`` for the value ``-1``.829-When using :class:`FloatRange`, ``clamp`` can only be enabled if both830-bounds are *closed* (the default).831-832-.. click:example::833-834- @click.command()835- @click.option("--count", type=click.IntRange(0, 20, clamp=True))836- @click.option("--digit", type=click.IntRange(0, 9))837- def repeat(count, digit):838- click.echo(str(digit) * count)839-840-.. click:run::841-842- invoke(repeat, args=['--count=100', '--digit=5'])843- invoke(repeat, args=['--count=6', '--digit=12'])844-845-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
1 unmodified line2 ==========3 4 .. currentmodule:: click5 6-Click supports only two types of parameters for scripts (by design): options and arguments.6+Click supports only two principle types of parameters for scripts (by design): options and arguments.7 8 Options9 ----------------10 13 unmodified lines24 * Can take an arbitrary number of arguments.25 * Are not fully documented by the help page since they may be too specific to be automatically documented. For more see :ref:`documenting-arguments`.26 * Can be pulled from environment variables but only explicitly named ones. For more see :ref:`environment-variables`.27 28+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.29+30 .. _parameter_names:31 32 Parameter Names33 ---------------19 unmodified lines53 54 .. click:run::55 56 invoke(multi_echo, ['--times=3', 'index.txt'], prog_name='multi_echo')55-56-Parameter Types57----------------58-59-The supported parameter types are:60-61-``str`` / :data:`click.STRING`:62- The default parameter type which indicates unicode strings.63-64-``int`` / :data:`click.INT`:65- A parameter that only accepts integers.66-67-``float`` / :data:`click.FLOAT`:68- A parameter that only accepts floating point values.69-70-``bool`` / :data:`click.BOOL`:71- A parameter that accepts boolean values. This is automatically used72- for boolean flags. The string values "1", "true", "t", "yes", "y",73- and "on" convert to ``True``. "0", "false", "f", "no", "n", and74- "off" convert to ``False``.75-76-:data:`click.UUID`:77- A parameter that accepts UUID values. This is not automatically78- guessed but represented as :class:`uuid.UUID`.79-80-.. autoclass:: File81- :noindex:82-83-.. autoclass:: Path84- :noindex:85-86-.. autoclass:: Choice87- :noindex:88-89-.. autoclass:: IntRange90- :noindex:91-92-.. autoclass:: FloatRange93- :noindex:94-95-.. autoclass:: DateTime96- :noindex:97-98-How to Implement Custom Types99--------------------------------100-101-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.102-103-The following code implements an integer type that accepts hex and octal104-numbers in addition to normal integers, and converts them into regular105-integers.106-107-.. code-block:: python108-109- import click110-111- class BasedIntParamType(click.ParamType):112- name = "integer"113-114- def convert(self, value, param, ctx):115- if isinstance(value, int):116- return value117-118- try:119- if value[:2].lower() == "0x":120- return int(value[2:], 16)121- elif value[:1] == "0":122- return int(value, 8)123- return int(value, 10)124- except ValueError:125- self.fail(f"{value!r} is not a valid integer", param, ctx)126-127- BASED_INT = BasedIntParamType()128-129-The :attr:`~ParamType.name` attribute is optional and is used for130-documentation. Call :meth:`~ParamType.fail` if conversion fails. The131-``param`` and ``ctx`` arguments may be ``None`` in some cases such as132-prompts.133-134-Values from user input or the command line will be strings, but default135-values and Python arguments may already be the correct type. The custom136-type should check at the top if the value is already valid and pass it137-through to support those cases.