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
Provenance
- Commit
ab21233- Tree
b467b7d- Author
Rowlando13 <67291205+Rowlando13@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent 1
f84395c- Parent 2
8c89a14
5 files changed+293 added−349 removed
modified:docs/advanced.rst+101 added-2 removed
6 unmodified lines7 itself, there are countless patterns that can be implemented by extending8 Click. This page should give some insight into what can be accomplished.9 10 .. contents::11- :depth: 112- :local:11+ :depth: 212+ :local:13 14+Callbacks and Eager Options15+---------------------------16+17+Sometimes, you want a parameter to completely change the execution flow.18+For instance, this is the case when you want to have a ``--version``19+parameter that prints out the version and then exits the application.20+21+Note: an actual implementation of a ``--version`` parameter that is22+reusable is available in Click as :func:`click.version_option`. The code23+here is merely an example of how to implement such a flag.24+25+In such cases, you need two concepts: eager parameters and a callback. An26+eager parameter is a parameter that is handled before others, and a27+callback is what executes after the parameter is handled. The eagerness28+is necessary so that an earlier required parameter does not produce an29+error message. For instance, if ``--version`` was not eager and a30+parameter ``--foo`` was required and defined before, you would need to31+specify it for ``--version`` to work. For more information, see32+:ref:`callback-evaluation-order`.33+34+A callback is a function that is invoked with three parameters: the35+current :class:`Context`, the current :class:`Parameter`, and the value.36+The context provides some useful features such as quitting the37+application and gives access to other already processed parameters.38+39+Here's an example for a ``--version`` flag:40+41+.. click:example::42+43+ def print_version(ctx, param, value):44+ if not value or ctx.resilient_parsing:45+ return46+ click.echo('Version 1.0')47+ ctx.exit()48+49+ @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!')54+55+The `expose_value` parameter prevents the pretty pointless ``version``56+parameter from being passed to the callback. If that was not specified, a57+boolean would be passed to the `hello` script. The `resilient_parsing`58+flag is applied to the context if Click wants to parse the command line59+without any destructive behavior that would change the execution flow. In60+this case, because we would exit the program, we instead do nothing.61+62+What it looks like:63+64+.. click:run::65+66+ invoke(hello)67+ invoke(hello, args=['--version'])68+69+Callbacks for Validation70+------------------------71+72+.. versionchanged:: 2.073+74+If you want to apply custom validation logic, you can do this in the75+parameter callbacks. These callbacks can both modify values as well as76+raise errors if the validation does not work. The callback runs after77+type conversion. It is called for all sources, including prompts.78+79+In Click 1.0, you can only raise the :exc:`UsageError` but starting with80+Click 2.0, you can also raise the :exc:`BadParameter` error, which has the81+added advantage that it will automatically format the error message to82+also contain the parameter name.83+84+.. click:example::85+86+ def validate_rolls(ctx, param, value):87+ if isinstance(value, tuple):88+ return value89+90+ try:91+ rolls, _, dice = value.partition("d")92+ return int(dice), int(rolls)93+ except ValueError:94+ raise click.BadParameter("format must be 'NdM'")95+96+ @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)")104+105+.. click:run::106+107+ invoke(roll, args=["--rolls=42"])108+ println()109+ invoke(roll, args=["--rolls=2d12"])110+ println()111+ invoke(roll, input=["42", "2d12"])112+113 .. _custom-groups:114 115 Custom Groups116 -------------547 unmodified linesmodified:docs/commands-and-groups.rst+51 added
214 unmodified lines215 216 Context Object217 -------------------218 The :class:`Context` object is how commands and groups communicate.219+220+Auto Envvar Prefix221+--------------------222+Automatically 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 subcommand223+called ``run`` taking an option called ``reload`` and the prefix is ``WEB``, then the variable is ``WEB_RUN_RELOAD``.224+225+Example usage:226+227+.. click:example::228+229+ @click.command()230+ @click.option('--username')231+ def greet(username):232+ click.echo(f'Hello {username}!')233+234+ if __name__ == '__main__':235+ greet(auto_envvar_prefix='GREETER')236+237+And from the command line:238+239+.. click:run::240+241+ invoke(greet, env={'GREETER_USERNAME': 'john'},242+ auto_envvar_prefix='GREETER')243+244+When using ``auto_envvar_prefix`` with command groups, the command name245+needs to be included in the environment variable, between the prefix and246+the parameter name, *i.e.* ``PREFIX_COMMAND_VARIABLE``. If you have a247+subcommand called ``run-server`` taking an option called ``host`` and248+the prefix is ``WEB``, then the variable is ``WEB_RUN_SERVER_HOST``.249+250+.. click:example::251+252+ @click.group()253+ @click.option('--debug/--no-debug')254+ def cli(debug):255+ click.echo(f"Debug mode is {'on' if debug else 'off'}")256+257+ @cli.command()258+ @click.option('--username')259+ def greet(username):260+ click.echo(f"Hello {username}!")261+262+ if __name__ == '__main__':263+ cli(auto_envvar_prefix='GREETER')264+265+.. click:run::266+267+ 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 lines77 @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!')81+82+Version 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 lines5 6 .. currentmodule:: click7 8 Adding options to commands can be accomplished with the :func:`option`9-decorator. Options in Click are distinct from :ref:`positional arguments <arguments>`.9+decorator. At runtime the decorator invokes the :class:`Option` class. Options in Click are distinct from :ref:`positional arguments <arguments>`.10 11 Useful and often used kwargs are:12 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`17+* ``type``: Sets :ref:`parameter type <parameter-types>`18 19 .. contents::20 :depth: 221 :local:182 unmodified lines204 205 invoke(log, args=[])206 invoke(log, args=['-vvv'])207 208+.. _option-boolean-flag:209+210 Boolean211 ------------------------212 213 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.68 unmodified lines282 invoke(info, args=['--help'])283 284 Flag Value285 ---------------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:286+To 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:287 288 .. click:example::289 290 import sys291 292 @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 line299 300 invoke(info, args=['--help'])301 invoke(info, args=['--upper'])302 invoke(info, args=['--lower'])301-302-Feature Switches303----------------------------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,308-Click will implicitly set ``is_flag=True``.309-310-To set a default flag, assign a value of `True` to the flag that should be311-the default.312-313-.. click:example::314-315- import sys316-317- @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)())323-324-.. click:run::325-326- invoke(info, args=['--upper'])327- invoke(info, args=['--help'])303 invoke(info)304 330-331-.. _option-prompting:332-333-Prompting334----------335-336-In some cases, you want parameters that can be provided from the command line,337-but if not provided, ask for user input instead. This can be implemented with338-Click by defining a prompt string.339-340-Example:341-342-.. click:example::343-344- @click.command()345- @click.option('--name', prompt=True)346- def hello(name):347- click.echo(f"Hello {name}!")348-349-And what it looks like:350-351-.. click:run::352-353- invoke(hello, args=['--name=John'])354- invoke(hello, input=['John'])355-356-If you are not happy with the default prompt string, you can ask for357-a different one:358-359-.. click:example::360-361- @click.command()362- @click.option('--name', prompt='Your name please')363- def hello(name):364- click.echo(f"Hello {name}!")365-366-What it looks like:367-368-.. click:run::369-370- invoke(hello, input=['John'])371-372-It is advised that prompt not be used in conjunction with the multiple373-flag set to True. Instead, prompt in the function interactively.374-375-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-379-Dynamic Defaults for Prompts380-----------------------------381-382-The ``auto_envvar_prefix`` and ``default_map`` options for the context383-allow the program to read option values from the environment or a384-configuration file. However, this overrides the prompting mechanism, so385-that the user does not get the option to change the value interactively.386-387-If you want to let the user configure the default value, but still be388-prompted if the option isn't specified on the command line, you can do so389-by supplying a callable as the default value. For example, to get a default390-from the environment:391-392-.. code-block:: python393-394- import os395-396- @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}!")403-404-To describe what the default value will be, set it in ``show_default``.405-406-.. click:example::407-408- import os409-410- @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}!")418-419-.. click:run::420-421- invoke(hello, args=["--help"])422-423-424-Callbacks and Eager Options425----------------------------426-427-Sometimes, you want a parameter to completely change the execution flow.428-For instance, this is the case when you want to have a ``--version``429-parameter that prints out the version and then exits the application.430-431-Note: an actual implementation of a ``--version`` parameter that is432-reusable is available in Click as :func:`click.version_option`. The code433-here is merely an example of how to implement such a flag.434-435-In such cases, you need two concepts: eager parameters and a callback. An436-eager parameter is a parameter that is handled before others, and a437-callback is what executes after the parameter is handled. The eagerness438-is necessary so that an earlier required parameter does not produce an439-error message. For instance, if ``--version`` was not eager and a440-parameter ``--foo`` was required and defined before, you would need to441-specify it for ``--version`` to work. For more information, see442-:ref:`callback-evaluation-order`.443-444-A callback is a function that is invoked with three parameters: the445-current :class:`Context`, the current :class:`Parameter`, and the value.446-The context provides some useful features such as quitting the447-application and gives access to other already processed parameters.448-449-Here's an example for a ``--version`` flag:450-451-.. click:example::452-453- def print_version(ctx, param, value):454- if not value or ctx.resilient_parsing:455- return456- click.echo('Version 1.0')457- ctx.exit()458-459- @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!')464-465-The `expose_value` parameter prevents the pretty pointless ``version``466-parameter from being passed to the callback. If that was not specified, a467-boolean would be passed to the `hello` script. The `resilient_parsing`468-flag is applied to the context if Click wants to parse the command line469-without any destructive behavior that would change the execution flow. In470-this case, because we would exit the program, we instead do nothing.471-472-What it looks like:473-474-.. click:run::475-476- invoke(hello)477- invoke(hello, args=['--version'])478-305 Values from Environment Variables306 ---------------------------------307+To pass in a value in from a specific environment variable use ``envvar``.308 482-A very useful feature of Click is the ability to accept parameters from483-environment variables in addition to regular parameters. This allows484-tools to be automated much easier. For instance, you might want to pass485-a configuration file with a ``--config`` parameter but also support exporting486-a ``TOOL_CONFIG=hello.cfg`` key-value pair for a nicer development487-experience.488-489-This is supported by Click in two ways. One is to automatically build490-environment variables which is supported for options only. To enable this491-feature, the ``auto_envvar_prefix`` parameter needs to be passed to the492-script that is invoked. Each command and parameter is then added as an493-uppercase underscore-separated variable. If you have a subcommand494-called ``run`` taking an option called ``reload`` and the prefix is495-``WEB``, then the variable is ``WEB_RUN_RELOAD``.496-497-Example usage:498-309 .. click:example::310 311 @click.command()502- @click.option('--username')312+ @click.option('--username', envvar='USERNAME')313 def greet(username):504- click.echo(f'Hello {username}!')505-506- if __name__ == '__main__':507- greet(auto_envvar_prefix='GREETER')508-509-And from the command line:510-511-.. click:run::512-513- invoke(greet, env={'GREETER_USERNAME': 'john'},514- auto_envvar_prefix='GREETER')515-516-When using ``auto_envvar_prefix`` with command groups, the command name517-needs to be included in the environment variable, between the prefix and518-the parameter name, *i.e.* ``PREFIX_COMMAND_VARIABLE``. If you have a519-subcommand called ``run-server`` taking an option called ``host`` and520-the prefix is ``WEB``, then the variable is ``WEB_RUN_SERVER_HOST``.521-522-Example:523-524-.. click:example::525-526- @click.group()527- @click.option('--debug/--no-debug')528- def cli(debug):529- click.echo(f"Debug mode is {'on' if debug else 'off'}")530-531- @cli.command()532- @click.option('--username')533- def greet(username):314 click.echo(f"Hello {username}!")315 536- if __name__ == '__main__':537- cli(auto_envvar_prefix='GREETER')538-316 .. click:run::317 541- invoke(cli, args=['greet',],542- env={'GREETER_GREET_USERNAME': 'John', 'GREETER_DEBUG': 'false'},543- auto_envvar_prefix='GREETER')318+ invoke(greet, env={'USERNAME': 'john'})319 320+If a list is passed to ``envvar``, the first environment variable found is picked.321 546-The second option is to manually pull values in from specific environment547-variables by defining the name of the environment variable on the option.548-549-Example usage:550-322 .. click:example::323 324 @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}!")328 558- if __name__ == '__main__':559- greet()560-561-And from the command line:562-329 .. click:run::330 565- invoke(greet, env={'USERNAME': 'john'})331+ invoke(greet, env={'ALT_USERNAME': 'Bill', 'USERNAME': 'john'})332 567-In that case it can also be a list of different environment variables568-where the first one is picked.333 570-Multiple Values from Environment Values571----------------------------------------334+Multiple Options from Environment Values335+-----------------------------------------336 337 As options can accept multiple values, pulling in such values from338 environment variables (which are strings) is a bit more complex. The way339 Click solves this is by leaving it up to the type to customize this3 unmodified lines343 344 The default implementation for all types is to split on whitespace. The345 exceptions to this rule are the :class:`File` and :class:`Path` types346 which both split according to the operating system's path splitting rules.583-On Unix systems like Linux and OS X, the splitting happens for those on584-every colon (``:``), and for Windows, on every semicolon (``;``).347+On Unix systems like Linux and OS X, the splitting happens on348+every colon (``:``), and for Windows, splitting on every semicolon (``;``).349 586-Example usage:587-350 .. click:example::351 352 @click.command()353 @click.option('paths', '--path', envvar='PATHS', multiple=True,4 unmodified lines358 359 if __name__ == '__main__':360 perform()361 600-And from the command line:601-362 .. click:run::363 364 import os365 invoke(perform, env={"PATHS": f"./foo/bar{os.path.pathsep}./test"})366 367 Other Prefix Characters368 -----------------------369 610-Click can deal with alternative prefix characters other than ``-`` for611-options. This is for instance useful if you want to handle slashes as612-parameters ``/`` or something similar. Note that this is strongly613-discouraged in general because Click wants developers to stay close to614-POSIX semantics. However in certain situations this can be useful:370+Click 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.372 373 .. click:example::374 375 @click.command()376 @click.option('+w/-w')377 def chmod(w):378 click.echo(f"writable={w}")379 623- if __name__ == '__main__':624- chmod()625-626-And from the command line:627-380 .. click:run::381 382 invoke(chmod, args=['+w'])383 invoke(chmod, args=['-w'])384 633-Note that if you are using ``/`` as prefix character and you want to use a634-boolean flag you need to separate it with ``;`` instead of ``/``:385+There are special considerations for using ``/`` as prefix character, see :ref:`option-boolean-flag` for more.386 636-.. click:example::637-638- @click.command()639- @click.option('/debug;/no-debug')640- def log(debug):641- click.echo(f"debug={debug}")642-643- if __name__ == '__main__':644- log()645-646-Callbacks for Validation647-------------------------648-649-.. versionchanged:: 2.0650-651-If you want to apply custom validation logic, you can do this in the652-parameter callbacks. These callbacks can both modify values as well as653-raise errors if the validation does not work. The callback runs after654-type conversion. It is called for all sources, including prompts.655-656-In Click 1.0, you can only raise the :exc:`UsageError` but starting with657-Click 2.0, you can also raise the :exc:`BadParameter` error, which has the658-added advantage that it will automatically format the error message to659-also contain the parameter name.660-661-.. click:example::662-663- def validate_rolls(ctx, param, value):664- if isinstance(value, tuple):665- return value666-667- try:668- rolls, _, dice = value.partition("d")669- return int(dice), int(rolls)670- except ValueError:671- raise click.BadParameter("format must be 'NdM'")672-673- @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)")681-682-.. click:run::683-684- invoke(roll, args=["--rolls=42"])685- println()686- invoke(roll, args=["--rolls=2d12"])687- println()688- invoke(roll, input=["42", "2d12"])689-690-387 .. _optional-value:388 389 Optional Value390 --------------2 unmodified lines393 providing only the option's flag without a value will either show a394 prompt or use its ``flag_value``.395 396 Setting ``is_flag=False, flag_value=value`` tells Click that the option701-can still be passed a value, but if only the flag is given the702-``flag_value`` is used.397+can still be passed a value, but only if the flag is given the398+``flag_value``.399 400 .. click:example::401 402 @click.command()5 unmodified lines408 409 invoke(hello, args=[])410 invoke(hello, args=["--name", "Value"])411 invoke(hello, args=["--name"])716-717-If the option has ``prompt`` enabled, then setting718-``prompt_required=False`` tells Click to only show the prompt if the719-option's flag is given, instead of if the option is not provided at all.720-721-.. click:example::722-723- @click.command()724- @click.option('--name', prompt=True, prompt_required=False, default="Default")725- def hello(name):726- click.echo(f"Hello {name}!")727-728-.. click:run::729-730- invoke(hello)731- invoke(hello, args=["--name", "Value"])732- invoke(hello, args=["--name"], input="Prompt")733-734-If ``required=True``, then the option will still prompt if it is not735-given, but it will also prompt if only the flag is given.modified:docs/prompts.rst+116 added-2 removed
9 unmodified lines10 This can be accomplished with the :func:`prompt` function, which asks for11 valid input according to a type, or the :func:`confirm` function, which asks12 for confirmation (yes/no).13 14+.. contents::15+ :depth: 216+ :local:17+18+.. _option-prompting:19+20 Option Prompts21 --------------22 17-Option prompts are integrated into the option interface. See18-:ref:`option-prompting` for more information. Internally, it23+Option prompts are integrated into the option interface. Internally, it24 automatically calls either :func:`prompt` or :func:`confirm` as necessary.25 26+In some cases, you want parameters that can be provided from the command line,27+but if not provided, ask for user input instead. This can be implemented with28+Click by defining a prompt string.29+30+Example:31+32+.. click:example::33+34+ @click.command()35+ @click.option('--name', prompt=True)36+ def hello(name):37+ click.echo(f"Hello {name}!")38+39+And what it looks like:40+41+.. click:run::42+43+ invoke(hello, args=['--name=John'])44+ invoke(hello, input=['John'])45+46+If you are not happy with the default prompt string, you can ask for47+a different one:48+49+.. click:example::50+51+ @click.command()52+ @click.option('--name', prompt='Your name please')53+ def hello(name):54+ click.echo(f"Hello {name}!")55+56+What it looks like:57+58+.. click:run::59+60+ invoke(hello, input=['John'])61+62+It is advised that prompt not be used in conjunction with the multiple63+flag set to True. Instead, prompt in the function interactively.64+65+By default, the user will be prompted for an input if one was not passed66+through the command line. To turn this behavior off, see67+:ref:`optional-value`.68+69 Input Prompts70 -------------71 72 To manually ask for user input, you can use the :func:`prompt` function.6 unmodified lines79 provided. For instance, the following will only accept floats::80 81 value = click.prompt('Please enter a number', default=42.0)82 83+Optional Prompts84+------------------85+If the option has ``prompt`` enabled, then setting86+``prompt_required=False`` tells Click to only show the prompt if the87+option's flag is given, instead of if the option is not provided at all.88+89+.. click:example::90+91+ @click.command()92+ @click.option('--name', prompt=True, prompt_required=False, default="Default")93+ def hello(name):94+ click.echo(f"Hello {name}!")95+96+.. click:run::97+98+ invoke(hello)99+ invoke(hello, args=["--name", "Value"])100+ invoke(hello, args=["--name"], input="Prompt")101+102+If ``required=True``, then the option will still prompt if it is not103+given, but it will also prompt if only the flag is given.104+105 Confirmation Prompts106 --------------------107 108 To ask if a user wants to continue with an action, the :func:`confirm`6 unmodified lines115 There is also the option to make the function automatically abort the116 execution of the program if it does not return ``True``::117 118 click.confirm('Do you want to continue?', abort=True)119+120+Dynamic Defaults for Prompts121+----------------------------122+123+The ``auto_envvar_prefix`` and ``default_map`` options for the context124+allow the program to read option values from the environment or a125+configuration file. However, this overrides the prompting mechanism, so126+that the user does not get the option to change the value interactively.127+128+If you want to let the user configure the default value, but still be129+prompted if the option isn't specified on the command line, you can do so130+by supplying a callable as the default value. For example, to get a default131+from the environment:132+133+.. code-block:: python134+135+ import os136+137+ @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}!")144+145+To describe what the default value will be, set it in ``show_default``.146+147+.. click:example::148+149+ import os150+151+ @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}!")159+160+.. click:run::161+162+ invoke(hello, args=["--help"])