Skip to content
Myr

Rewrite second half of options docs (#2848)

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

Rewrite second half of options docs. Sections moved: - Callbacks and Eager Options from options to advanced - Callbacks for Validation from options to advanced - Auto Envvar Prefix from options to commands-and-groups - Option prompts from options to prompts - Optional prompts from options to prompts - Dynamic Default for Prompts from options to prompts Changes: - Version option added - Flag value rewritten - Feature Switches merged into Flag Value

authored by Rowlando13 · committed by GitHub · parents f84395c, 8c89a14 · Browse files · 5 files+293 added−349 removed
This commit

State

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

Diff stats

5 files+293 added−349 removed

  • other:+293 added−349 removed

5 files+293 added−349 removed

modified:docs/advanced.rst+101 added-2 removed
6 unmodified lines
7itself, there are countless patterns that can be implemented by extending8Click. This page should give some insight into what can be accomplished.910.. contents::11 :depth: 112 :local:11 :depth: 212 :local:1314Callbacks and Eager Options15---------------------------1617Sometimes, you want a parameter to completely change the execution flow.18For instance, this is the case when you want to have a ``--version``19parameter that prints out the version and then exits the application.2021Note: an actual implementation of a ``--version`` parameter that is22reusable is available in Click as :func:`click.version_option`. The code23here is merely an example of how to implement such a flag.2425In such cases, you need two concepts: eager parameters and a callback. An26eager parameter is a parameter that is handled before others, and a27callback is what executes after the parameter is handled. The eagerness28is necessary so that an earlier required parameter does not produce an29error message. For instance, if ``--version`` was not eager and a30parameter ``--foo`` was required and defined before, you would need to31specify it for ``--version`` to work. For more information, see32:ref:`callback-evaluation-order`.3334A callback is a function that is invoked with three parameters: the35current :class:`Context`, the current :class:`Parameter`, and the value.36The context provides some useful features such as quitting the37application and gives access to other already processed parameters.3839Here's an example for a ``--version`` flag:4041.. click:example::4243 def print_version(ctx, param, value):44 if not value or ctx.resilient_parsing:45 return46 click.echo('Version 1.0')47 ctx.exit()4849 @click.command()50 @click.option('--version', is_flag=True, callback=print_version,51 expose_value=False, is_eager=True)52 def hello():53 click.echo('Hello World!')5455The `expose_value` parameter prevents the pretty pointless ``version``56parameter from being passed to the callback. If that was not specified, a57boolean would be passed to the `hello` script. The `resilient_parsing`58flag is applied to the context if Click wants to parse the command line59without any destructive behavior that would change the execution flow. In60this case, because we would exit the program, we instead do nothing.6162What it looks like:6364.. click:run::6566 invoke(hello)67 invoke(hello, args=['--version'])6869Callbacks for Validation70------------------------7172.. versionchanged:: 2.07374If you want to apply custom validation logic, you can do this in the75parameter callbacks. These callbacks can both modify values as well as76raise errors if the validation does not work. The callback runs after77type conversion. It is called for all sources, including prompts.7879In Click 1.0, you can only raise the :exc:`UsageError` but starting with80Click 2.0, you can also raise the :exc:`BadParameter` error, which has the81added advantage that it will automatically format the error message to82also contain the parameter name.8384.. click:example::8586 def validate_rolls(ctx, param, value):87 if isinstance(value, tuple):88 return value8990 try:91 rolls, _, dice = value.partition("d")92 return int(dice), int(rolls)93 except ValueError:94 raise click.BadParameter("format must be 'NdM'")9596 @click.command()97 @click.option(98 "--rolls", type=click.UNPROCESSED, callback=validate_rolls,99 default="1d6", prompt=True,100 )101 def roll(rolls):102 sides, times = rolls103 click.echo(f"Rolling a {sides}-sided dice {times} time(s)")104105.. click:run::106107 invoke(roll, args=["--rolls=42"])108 println()109 invoke(roll, args=["--rolls=2d12"])110 println()111 invoke(roll, input=["42", "2d12"])112113.. _custom-groups:114115Custom Groups116-------------
547 unmodified lines
modified:docs/commands-and-groups.rst+51 added
214 unmodified lines
215216Context Object217-------------------218The :class:`Context` object is how commands and groups communicate.219220Auto Envvar Prefix221--------------------222Automatically built environment variables are supported for options only. To enable this feature, the ``auto_envvar_prefix`` parameter needs to be passed to the script that is invoked. Each command and parameter is then added as an uppercase underscore-separated variable. If you have a subcommand223called ``run`` taking an option called ``reload`` and the prefix is ``WEB``, then the variable is ``WEB_RUN_RELOAD``.224225Example usage:226227.. click:example::228229 @click.command()230 @click.option('--username')231 def greet(username):232 click.echo(f'Hello {username}!')233234 if __name__ == '__main__':235 greet(auto_envvar_prefix='GREETER')236237And from the command line:238239.. click:run::240241 invoke(greet, env={'GREETER_USERNAME': 'john'},242 auto_envvar_prefix='GREETER')243244When using ``auto_envvar_prefix`` with command groups, the command name245needs to be included in the environment variable, between the prefix and246the parameter name, *i.e.* ``PREFIX_COMMAND_VARIABLE``. If you have a247subcommand called ``run-server`` taking an option called ``host`` and248the prefix is ``WEB``, then the variable is ``WEB_RUN_SERVER_HOST``.249250.. click:example::251252 @click.group()253 @click.option('--debug/--no-debug')254 def cli(debug):255 click.echo(f"Debug mode is {'on' if debug else 'off'}")256257 @cli.command()258 @click.option('--username')259 def greet(username):260 click.echo(f"Hello {username}!")261262 if __name__ == '__main__':263 cli(auto_envvar_prefix='GREETER')264265.. click:run::266267 invoke(cli, args=['greet',],268 env={'GREETER_GREET_USERNAME': 'John', 'GREETER_DEBUG': 'false'},269 auto_envvar_prefix='GREETER')
modified:docs/option-decorators.rst+4 added
76 unmodified lines
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!')8182Version Option83----------------84:func:`version_option` adds a ``--version`` option which immediately prints the version number and exits the program.
modified:docs/options.rst+21 added-345 removed
4 unmodified lines
56.. currentmodule:: click78Adding options to commands can be accomplished with the :func:`option`9decorator. Options in Click are distinct from :ref:`positional arguments <arguments>`.9decorator. At runtime the decorator invokes the :class:`Option` class. Options in Click are distinct from :ref:`positional arguments <arguments>`.1011Useful and often used kwargs are:1213* ``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`17* ``type``: Sets :ref:`parameter type <parameter-types>`1819.. contents::20 :depth: 221 :local:
182 unmodified lines
204205 invoke(log, args=[])206 invoke(log, args=['-vvv'])207208.. _option-boolean-flag:209210Boolean211------------------------212213Boolean 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.
68 unmodified lines
282 invoke(info, args=['--help'])283284Flag Value285---------------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:286To have an flag pass a value to the underlying function set ``flag_value``. This automatically sets ``is_flag=True``. To set a default flag, set ``default=True``. Setting flag values can be used to create patterns like this:287288.. click:example::289290 import sys291292 @click.command()291 @click.option('--upper', 'transformation', flag_value='upper')293 @click.option('--upper', 'transformation', flag_value='upper', default=True)294 @click.option('--lower', 'transformation', flag_value='lower')295 def info(transformation):296 click.echo(getattr(sys.platform, transformation)())297
1 unmodified line
299300 invoke(info, args=['--help'])301 invoke(info, args=['--upper'])302 invoke(info, args=['--lower'])301302Feature Switches303---------------------------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,308Click will implicitly set ``is_flag=True``.309310To set a default flag, assign a value of `True` to the flag that should be311the default.312313.. click:example::314315 import sys316317 @click.command()318 @click.option('--upper', 'transformation', flag_value='upper',319 default=True)320 @click.option('--lower', 'transformation', flag_value='lower')321 def info(transformation):322 click.echo(getattr(sys.platform, transformation)())323324.. click:run::325326 invoke(info, args=['--upper'])327 invoke(info, args=['--help'])303 invoke(info)304330331.. _option-prompting:332333Prompting334---------335336In some cases, you want parameters that can be provided from the command line,337but if not provided, ask for user input instead. This can be implemented with338Click by defining a prompt string.339340Example:341342.. click:example::343344 @click.command()345 @click.option('--name', prompt=True)346 def hello(name):347 click.echo(f"Hello {name}!")348349And what it looks like:350351.. click:run::352353 invoke(hello, args=['--name=John'])354 invoke(hello, input=['John'])355356If you are not happy with the default prompt string, you can ask for357a different one:358359.. click:example::360361 @click.command()362 @click.option('--name', prompt='Your name please')363 def hello(name):364 click.echo(f"Hello {name}!")365366What it looks like:367368.. click:run::369370 invoke(hello, input=['John'])371372It is advised that prompt not be used in conjunction with the multiple373flag set to True. Instead, prompt in the function interactively.374375By 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`.378379Dynamic Defaults for Prompts380----------------------------381382The ``auto_envvar_prefix`` and ``default_map`` options for the context383allow the program to read option values from the environment or a384configuration file. However, this overrides the prompting mechanism, so385that the user does not get the option to change the value interactively.386387If you want to let the user configure the default value, but still be388prompted if the option isn't specified on the command line, you can do so389by supplying a callable as the default value. For example, to get a default390from the environment:391392.. code-block:: python393394 import os395396 @click.command()397 @click.option(398 "--username", prompt=True,399 default=lambda: os.environ.get("USER", "")400 )401 def hello(username):402 click.echo(f"Hello, {username}!")403404To describe what the default value will be, set it in ``show_default``.405406.. click:example::407408 import os409410 @click.command()411 @click.option(412 "--username", prompt=True,413 default=lambda: os.environ.get("USER", ""),414 show_default="current user"415 )416 def hello(username):417 click.echo(f"Hello, {username}!")418419.. click:run::420421 invoke(hello, args=["--help"])422423424Callbacks and Eager Options425---------------------------426427Sometimes, you want a parameter to completely change the execution flow.428For instance, this is the case when you want to have a ``--version``429parameter that prints out the version and then exits the application.430431Note: an actual implementation of a ``--version`` parameter that is432reusable is available in Click as :func:`click.version_option`. The code433here is merely an example of how to implement such a flag.434435In such cases, you need two concepts: eager parameters and a callback. An436eager parameter is a parameter that is handled before others, and a437callback is what executes after the parameter is handled. The eagerness438is necessary so that an earlier required parameter does not produce an439error message. For instance, if ``--version`` was not eager and a440parameter ``--foo`` was required and defined before, you would need to441specify it for ``--version`` to work. For more information, see442:ref:`callback-evaluation-order`.443444A callback is a function that is invoked with three parameters: the445current :class:`Context`, the current :class:`Parameter`, and the value.446The context provides some useful features such as quitting the447application and gives access to other already processed parameters.448449Here's an example for a ``--version`` flag:450451.. click:example::452453 def print_version(ctx, param, value):454 if not value or ctx.resilient_parsing:455 return456 click.echo('Version 1.0')457 ctx.exit()458459 @click.command()460 @click.option('--version', is_flag=True, callback=print_version,461 expose_value=False, is_eager=True)462 def hello():463 click.echo('Hello World!')464465The `expose_value` parameter prevents the pretty pointless ``version``466parameter from being passed to the callback. If that was not specified, a467boolean would be passed to the `hello` script. The `resilient_parsing`468flag is applied to the context if Click wants to parse the command line469without any destructive behavior that would change the execution flow. In470this case, because we would exit the program, we instead do nothing.471472What it looks like:473474.. click:run::475476 invoke(hello)477 invoke(hello, args=['--version'])478305Values from Environment Variables306---------------------------------307To pass in a value in from a specific environment variable use ``envvar``.308482A very useful feature of Click is the ability to accept parameters from483environment variables in addition to regular parameters. This allows484tools to be automated much easier. For instance, you might want to pass485a configuration file with a ``--config`` parameter but also support exporting486a ``TOOL_CONFIG=hello.cfg`` key-value pair for a nicer development487experience.488489This is supported by Click in two ways. One is to automatically build490environment variables which is supported for options only. To enable this491feature, the ``auto_envvar_prefix`` parameter needs to be passed to the492script that is invoked. Each command and parameter is then added as an493uppercase underscore-separated variable. If you have a subcommand494called ``run`` taking an option called ``reload`` and the prefix is495``WEB``, then the variable is ``WEB_RUN_RELOAD``.496497Example usage:498309.. click:example::310311 @click.command()502 @click.option('--username')312 @click.option('--username', envvar='USERNAME')313 def greet(username):504 click.echo(f'Hello {username}!')505506 if __name__ == '__main__':507 greet(auto_envvar_prefix='GREETER')508509And from the command line:510511.. click:run::512513 invoke(greet, env={'GREETER_USERNAME': 'john'},514 auto_envvar_prefix='GREETER')515516When using ``auto_envvar_prefix`` with command groups, the command name517needs to be included in the environment variable, between the prefix and518the parameter name, *i.e.* ``PREFIX_COMMAND_VARIABLE``. If you have a519subcommand called ``run-server`` taking an option called ``host`` and520the prefix is ``WEB``, then the variable is ``WEB_RUN_SERVER_HOST``.521522Example:523524.. click:example::525526 @click.group()527 @click.option('--debug/--no-debug')528 def cli(debug):529 click.echo(f"Debug mode is {'on' if debug else 'off'}")530531 @cli.command()532 @click.option('--username')533 def greet(username):314 click.echo(f"Hello {username}!")315536 if __name__ == '__main__':537 cli(auto_envvar_prefix='GREETER')538316.. click:run::317541 invoke(cli, args=['greet',],542 env={'GREETER_GREET_USERNAME': 'John', 'GREETER_DEBUG': 'false'},543 auto_envvar_prefix='GREETER')318 invoke(greet, env={'USERNAME': 'john'})319320If a list is passed to ``envvar``, the first environment variable found is picked.321546The second option is to manually pull values in from specific environment547variables by defining the name of the environment variable on the option.548549Example usage:550322.. click:example::323324 @click.command()554 @click.option('--username', envvar='USERNAME')325 @click.option('--username', envvar=['ALT_USERNAME', 'USERNAME'])326 def greet(username):327 click.echo(f"Hello {username}!")328558 if __name__ == '__main__':559 greet()560561And from the command line:562329.. click:run::330565 invoke(greet, env={'USERNAME': 'john'})331 invoke(greet, env={'ALT_USERNAME': 'Bill', 'USERNAME': 'john'})332567In that case it can also be a list of different environment variables568where the first one is picked.333570Multiple Values from Environment Values571---------------------------------------334Multiple Options from Environment Values335-----------------------------------------336337As options can accept multiple values, pulling in such values from338environment variables (which are strings) is a bit more complex. The way339Click solves this is by leaving it up to the type to customize this
3 unmodified lines
343344The default implementation for all types is to split on whitespace. The345exceptions to this rule are the :class:`File` and :class:`Path` types346which both split according to the operating system's path splitting rules.583On Unix systems like Linux and OS X, the splitting happens for those on584every colon (``:``), and for Windows, on every semicolon (``;``).347On Unix systems like Linux and OS X, the splitting happens on348every colon (``:``), and for Windows, splitting on every semicolon (``;``).349586Example usage:587350.. click:example::351352 @click.command()353 @click.option('paths', '--path', envvar='PATHS', multiple=True,
4 unmodified lines
358359 if __name__ == '__main__':360 perform()361600And from the command line:601362.. click:run::363364 import os365 invoke(perform, env={"PATHS": f"./foo/bar{os.path.pathsep}./test"})366367Other Prefix Characters368-----------------------369610Click can deal with alternative prefix characters other than ``-`` for611options. This is for instance useful if you want to handle slashes as612parameters ``/`` or something similar. Note that this is strongly613discouraged in general because Click wants developers to stay close to614POSIX semantics. However in certain situations this can be useful:370Click can deal with prefix characters besides ``-`` for options. Click can use371``/``, ``+`` as well as others. Note that alternative prefix characters are generally used very sparingly if at all within POSIX.372373.. click:example::374375 @click.command()376 @click.option('+w/-w')377 def chmod(w):378 click.echo(f"writable={w}")379623 if __name__ == '__main__':624 chmod()625626And from the command line:627380.. click:run::381382 invoke(chmod, args=['+w'])383 invoke(chmod, args=['-w'])384633Note that if you are using ``/`` as prefix character and you want to use a634boolean flag you need to separate it with ``;`` instead of ``/``:385There are special considerations for using ``/`` as prefix character, see :ref:`option-boolean-flag` for more.386636.. click:example::637638 @click.command()639 @click.option('/debug;/no-debug')640 def log(debug):641 click.echo(f"debug={debug}")642643 if __name__ == '__main__':644 log()645646Callbacks for Validation647------------------------648649.. versionchanged:: 2.0650651If you want to apply custom validation logic, you can do this in the652parameter callbacks. These callbacks can both modify values as well as653raise errors if the validation does not work. The callback runs after654type conversion. It is called for all sources, including prompts.655656In Click 1.0, you can only raise the :exc:`UsageError` but starting with657Click 2.0, you can also raise the :exc:`BadParameter` error, which has the658added advantage that it will automatically format the error message to659also contain the parameter name.660661.. click:example::662663 def validate_rolls(ctx, param, value):664 if isinstance(value, tuple):665 return value666667 try:668 rolls, _, dice = value.partition("d")669 return int(dice), int(rolls)670 except ValueError:671 raise click.BadParameter("format must be 'NdM'")672673 @click.command()674 @click.option(675 "--rolls", type=click.UNPROCESSED, callback=validate_rolls,676 default="1d6", prompt=True,677 )678 def roll(rolls):679 sides, times = rolls680 click.echo(f"Rolling a {sides}-sided dice {times} time(s)")681682.. click:run::683684 invoke(roll, args=["--rolls=42"])685 println()686 invoke(roll, args=["--rolls=2d12"])687 println()688 invoke(roll, input=["42", "2d12"])689690387.. _optional-value:388389Optional Value390--------------
2 unmodified lines
393providing only the option's flag without a value will either show a394prompt or use its ``flag_value``.395396Setting ``is_flag=False, flag_value=value`` tells Click that the option701can still be passed a value, but if only the flag is given the702``flag_value`` is used.397can still be passed a value, but only if the flag is given the398``flag_value``.399400.. click:example::401402 @click.command()
5 unmodified lines
408409 invoke(hello, args=[])410 invoke(hello, args=["--name", "Value"])411 invoke(hello, args=["--name"])716717If the option has ``prompt`` enabled, then setting718``prompt_required=False`` tells Click to only show the prompt if the719option's flag is given, instead of if the option is not provided at all.720721.. click:example::722723 @click.command()724 @click.option('--name', prompt=True, prompt_required=False, default="Default")725 def hello(name):726 click.echo(f"Hello {name}!")727728.. click:run::729730 invoke(hello)731 invoke(hello, args=["--name", "Value"])732 invoke(hello, args=["--name"], input="Prompt")733734If ``required=True``, then the option will still prompt if it is not735given, but it will also prompt if only the flag is given.
modified:docs/prompts.rst+116 added-2 removed
9 unmodified lines
10This can be accomplished with the :func:`prompt` function, which asks for11valid input according to a type, or the :func:`confirm` function, which asks12for confirmation (yes/no).1314.. contents::15 :depth: 216 :local:1718.. _option-prompting:1920Option Prompts21--------------2217Option prompts are integrated into the option interface. See18:ref:`option-prompting` for more information. Internally, it23Option prompts are integrated into the option interface. Internally, it24automatically calls either :func:`prompt` or :func:`confirm` as necessary.2526In some cases, you want parameters that can be provided from the command line,27but if not provided, ask for user input instead. This can be implemented with28Click by defining a prompt string.2930Example:3132.. click:example::3334 @click.command()35 @click.option('--name', prompt=True)36 def hello(name):37 click.echo(f"Hello {name}!")3839And what it looks like:4041.. click:run::4243 invoke(hello, args=['--name=John'])44 invoke(hello, input=['John'])4546If you are not happy with the default prompt string, you can ask for47a different one:4849.. click:example::5051 @click.command()52 @click.option('--name', prompt='Your name please')53 def hello(name):54 click.echo(f"Hello {name}!")5556What it looks like:5758.. click:run::5960 invoke(hello, input=['John'])6162It is advised that prompt not be used in conjunction with the multiple63flag set to True. Instead, prompt in the function interactively.6465By default, the user will be prompted for an input if one was not passed66through the command line. To turn this behavior off, see67:ref:`optional-value`.6869Input Prompts70-------------7172To manually ask for user input, you can use the :func:`prompt` function.
6 unmodified lines
79provided. For instance, the following will only accept floats::8081 value = click.prompt('Please enter a number', default=42.0)8283Optional Prompts84------------------85If the option has ``prompt`` enabled, then setting86``prompt_required=False`` tells Click to only show the prompt if the87option's flag is given, instead of if the option is not provided at all.8889.. click:example::9091 @click.command()92 @click.option('--name', prompt=True, prompt_required=False, default="Default")93 def hello(name):94 click.echo(f"Hello {name}!")9596.. click:run::9798 invoke(hello)99 invoke(hello, args=["--name", "Value"])100 invoke(hello, args=["--name"], input="Prompt")101102If ``required=True``, then the option will still prompt if it is not103given, but it will also prompt if only the flag is given.104105Confirmation Prompts106--------------------107108To ask if a user wants to continue with an action, the :func:`confirm`
6 unmodified lines
115There is also the option to make the function automatically abort the116execution of the program if it does not return ``True``::117118 click.confirm('Do you want to continue?', abort=True)119120Dynamic Defaults for Prompts121----------------------------122123The ``auto_envvar_prefix`` and ``default_map`` options for the context124allow the program to read option values from the environment or a125configuration file. However, this overrides the prompting mechanism, so126that the user does not get the option to change the value interactively.127128If you want to let the user configure the default value, but still be129prompted if the option isn't specified on the command line, you can do so130by supplying a callable as the default value. For example, to get a default131from the environment:132133.. code-block:: python134135 import os136137 @click.command()138 @click.option(139 "--username", prompt=True,140 default=lambda: os.environ.get("USER", "")141 )142 def hello(username):143 click.echo(f"Hello, {username}!")144145To describe what the default value will be, set it in ``show_default``.146147.. click:example::148149 import os150151 @click.command()152 @click.option(153 "--username", prompt=True,154 default=lambda: os.environ.get("USER", ""),155 show_default="current user"156 )157 def hello(username):158 click.echo(f"Hello, {username}!")159160.. click:run::161162 invoke(hello, args=["--help"])