Skip to content
Myr

Merge branch 'stable' into fix_prompt_suffix

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

authored by Gene Wood · committed by Gene Wood · parents 2608132, 27aaed3 · Browse files · 12 files+613 added−517 removed
This commit

State

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

Diff stats

12 files+613 added−517 removed

  • tests:+63 added−9 removed
  • other:+550 added−508 removed

12 files+613 added−517 removed

added:docs/advanced.md+415 added
1# Advanced Patterns23```{currentmodule} click4```56In addition to common functionality, Click offers some advanced features.78```{contents}9:depth: 110:local: true11```1213## Callbacks and Eager Options1415Sometimes, you want a parameter to completely change the execution flow.16For instance, this is the case when you want to have a `--version`17parameter that prints out the version and then exits the application.1819Note: an actual implementation of a `--version` parameter that is20reusable is available in Click as {func}`click.version_option`. The code21here is merely an example of how to implement such a flag.2223In such cases, you need two concepts: eager parameters and a callback. An24eager parameter is a parameter handled before others, and a25callback is what executes after the parameter is handled. The eagerness26is necessary so that an earlier required parameter does not produce an27error message. For instance, if `--version` was not eager and a28parameter `--foo` was required and defined before, you would need to29specify it for `--version` to work. For more information, see30{ref}`callback-evaluation-order`.3132A callback is a function invoked with three parameters: the33current {class}`Context`, the current {class}`Parameter`, and the value.34The context provides some useful features such as quitting the35application and gives access to other already processed parameters.3637Here's an example for a `--version` flag:3839```{eval-rst}40.. click:example::4142 def print_version(ctx, param, value):43 if not value or ctx.resilient_parsing:44 return45 click.echo('Version 1.0')46 ctx.exit()4748 @click.command()49 @click.option('--version', is_flag=True, callback=print_version,50 expose_value=False, is_eager=True)51 def hello():52 click.echo('Hello World!')535455What it looks like:565758.. click:run::5960 invoke(hello)61 invoke(hello, args=['--version'])62```63The `expose_value` parameter prevents the pretty pointless `version`64parameter from being passed to the callback. If that was not specified, a65boolean would be passed to the `hello` script. The `resilient_parsing`66flag is applied to the context if Click wants to parse the command line67without any destructive behavior that would change the execution flow. In68this case, because we would exit the program, we instead do nothing.6970## Callbacks for Validation7172```{versionchanged} 2.073```7475If you want to apply custom validation logic, you can do this in the76parameter callbacks. These callbacks can both modify values and77raise errors if the validation does not work. The callback runs after78type conversion. It is called for all sources, including prompts.7980In Click 1.0, you can only raise the {exc}`UsageError` but starting with81Click 2.0, you can also raise the {exc}`BadParameter` error, which has the82added advantage that it will automatically format the error message to83also contain the parameter name.8485```{eval-rst}86.. click:example::8788 def validate_rolls(ctx, param, value):89 if isinstance(value, tuple):90 return value9192 try:93 rolls, _, dice = value.partition("d")94 return int(dice), int(rolls)95 except ValueError:96 raise click.BadParameter("format must be 'NdM'")9798 @click.command()99 @click.option(100 "--rolls", type=click.UNPROCESSED, callback=validate_rolls,101 default="1d6", prompt=True,102 )103 def roll(rolls):104 sides, times = rolls105 click.echo(f"Rolling a {sides}-sided dice {times} time(s)")106107.. click:run::108109 invoke(roll, args=["--rolls=42"])110 println()111 invoke(roll, args=["--rolls=2d12"])112 println()113 invoke(roll, input=["42", "2d12"])114```115116## Parameter Modifications117118Parameters (options and arguments) are forwarded to the command callbacks,119as you have seen. One common way to prevent a parameter from being passed120to the callback is the `expose_value` argument to a parameter which hides121the parameter entirely. The way this works is that the {class}`Context`122object has a {attr}`~Context.params` attribute which is a dictionary of123all parameters. Whatever is in that dictionary is being passed to the124callbacks.125126This can be used to make up additional parameters. Generally, this pattern127is not recommended, but in some cases it can be useful. At the very least,128it's good to know that the system works this way.129130```{eval-rst}131.. click:example::132133 import urllib134135 def open_url(ctx, param, value):136 if value is not None:137 ctx.params['fp'] = urllib.urlopen(value)138 return value139140 @click.command()141 @click.option('--url', callback=open_url)142 def cli(url, fp=None):143 if fp is not None:144 click.echo(f"{url}: {fp.code}")145146In this case the callback returns the URL unchanged but also passes a147second `fp` value to the callback. What's more recommended is to pass148the information in a wrapper, however:149150.. click:example::151152 import urllib153154 class URL(object):155156 def __init__(self, url, fp):157 self.url = url158 self.fp = fp159160 def open_url(ctx, param, value):161 if value is not None:162 return URL(value, urllib.urlopen(value))163164 @click.command()165 @click.option('--url', callback=open_url)166 def cli(url):167 if url is not None:168 click.echo(f"{url.url}: {url.fp.code}")169170```171172## Token Normalization173174```{versionadded} 2.0175```176177Starting with Click 2.0, it's possible to provide a function used178for normalizing tokens. Tokens are option names, choice values, or command179values. This can be used to implement case-insensitive options, for180instance.181182To use this feature, the context needs to be passed a function that183performs the normalization of the token. Such as a function that converts the184token to lowercase:185186```{eval-rst}187.. click:example::188189 CONTEXT_SETTINGS = dict(token_normalize_func=lambda x: x.lower())190191 @click.command(context_settings=CONTEXT_SETTINGS)192 @click.option('--name', default='Pete')193 def cli(name):194 click.echo(f"Name: {name}")195196# And how it works on the command line:197198.. click:run::199200 invoke(cli, prog_name='cli', args=['--NAME=Pete'])201```202203## Invoking Other Commands204205Sometimes, it might be interesting to invoke one command from another206command. This is a pattern generally discouraged with Click, but207possible nonetheless. For this, you can use the {func}`Context.invoke`208or {func}`Context.forward` methods.209210They work similarly, but the difference is that {func}`Context.invoke` merely211invokes another command with the arguments you provide as a caller,212whereas {func}`Context.forward` fills in the arguments from the current213command. Both accept the command as the first argument, and everything else214is passed onwards as you would expect.215216Example:217218```{eval-rst}219.. click:example::220221 cli = click.Group()222223 @cli.command()224 @click.option('--count', default=1)225 def test(count):226 click.echo(f'Count: {count}')227228 @cli.command()229 @click.option('--count', default=1)230 @click.pass_context231 def dist(ctx, count):232 ctx.forward(test)233 ctx.invoke(test, count=42)234235And what it looks like:236237.. click:run::238239 invoke(cli, prog_name='cli', args=['dist'])240```241242(forwarding-unknown-options)=243244## Forwarding Unknown Options245246In some situations, it is interesting to be able to accept all unknown247options for further manual processing. Click can generally do that as of248Click 4.0, but it has some limitations that lie in the nature of the249problem. The support for this is provided through a parser flag called250`ignore_unknown_options` which will instruct the parser to collect all251unknown options and to put them to the leftover argument instead of252triggering a parsing error.253254This can generally be activated in two different ways:2552561. It can be enabled on custom {class}`Command` subclasses by changing257 the {attr}`~Command.ignore_unknown_options` attribute.2582. It can be enabled by changing the attribute of the same name on the259 context class ({attr}`Context.ignore_unknown_options`). This is best260 changed through the `context_settings` dictionary on the command.261262For most situations, the easiest solution is the second. Once the behavior263is changed, something needs to pick up those leftover options (which at264this point are considered arguments). For this again, you have two265options:2662671. You can use {func}`pass_context` to get the context passed. This will268 only work if in addition to {attr}`~Context.ignore_unknown_options`269 you also set {attr}`~Context.allow_extra_args` as otherwise the270 command will abort with an error that there are leftover arguments.271 If you go with this solution, the extra arguments will be collected in272 {attr}`Context.args`.2732. You can attach an {func}`argument` with `nargs` set to `-1` which274 will eat up all leftover arguments. In this case it's recommended to275 set the `type` to {data}`UNPROCESSED` to avoid any string processing276 on those arguments as otherwise they are forced into Unicode strings277 automatically which is often not what you want.278279In the end, the result looks something like this:280281```{eval-rst}282.. click:example::283284 import sys285 from subprocess import call286287 @click.command(context_settings=dict(288 ignore_unknown_options=True,289 ))290 @click.option('-v', '--verbose', is_flag=True, help='Enables verbose mode')291 @click.argument('timeit_args', nargs=-1, type=click.UNPROCESSED)292 def cli(verbose, timeit_args):293 """A fake wrapper around Python's timeit."""294 cmdline = ['echo', 'python', '-mtimeit'] + list(timeit_args)295 if verbose:296 click.echo(f"Invoking: {' '.join(cmdline)}")297 call(cmdline)298299300And the final output resembles the following:301302.. click:run::303304 invoke(cli, prog_name='cli', args=['--help'])305 println()306 invoke(cli, prog_name='cli', args=['-n', '100', 'a = 1; b = 2; a * b'])307 println()308 invoke(cli, prog_name='cli', args=['-v', 'a = 1; b = 2; a * b'])309```310311As you can see, Click handles the verbosity flag and everything else312ends up in the `timeit_args` variable for further processing, which then313for instance, allows invoking a subprocess. There are a few things that314are important to know about how this ignoring of unhandled flag happens:315316- Unknown long options are generally ignored and not processed at all.317 So for instance if `--foo=bar` or `--foo bar` are passed they318 generally end up like that. Note that because the parser cannot know319 if an option will accept an argument or not, the `bar` part might be320 handled as an argument.321- Unknown short options might be partially handled and reassembled if322 necessary. For instance in the above example there is an option323 called `-v` which enables verbose mode. If the command would be324 ignored with `-va` then the `-v` part would be handled by Click325 (as it is known) and `-a` would end up in the leftover parameters326 for further processing.327- Depending on what you plan on doing you might have some success by328 disabling interspersed arguments329 ({attr}`~Context.allow_interspersed_args`) which instructs the parser330 to not allow arguments and options to be mixed. Depending on your331 situation, this might improve your results.332333Generally, combining the handling of options and arguments from your own334commands with those from another application is discouraged, and you335should avoid it if possible. It's a much better idea to have336everything below a subcommand be forwarded to another application than to337handle some arguments yourself.338339## Managing Resources340341It can be useful to open a resource in a group, to be made available to342subcommands. Many types of resources need to be closed or otherwise343cleaned up after use. The standard way to do this in Python is by using344a context manager with the `with` statement.345346For example, the `Repo` class from {doc}`complex` might actually be347defined as a context manager:348349```python350class Repo:351 def __init__(self, home=None):352 self.home = os.path.abspath(home or ".")353 self.db = None354355 def __enter__(self):356 path = os.path.join(self.home, "repo.db")357 self.db = open_database(path)358 return self359360 def __exit__(self, exc_type, exc_value, tb):361 self.db.close()362```363364Ordinarily, it would be used with the `with` statement:365366```python367with Repo() as repo:368 repo.db.query(...)369```370371However, a `with` block in a group would exit and close the database372before it could be used by a subcommand.373374Instead, use the context's {meth}`~click.Context.with_resource` method375to enter the context manager and return the resource. When the group and376any subcommands finish, the context's resources are cleaned up.377378```python379@click.group()380@click.option("--repo-home", default=".repo")381@click.pass_context382def cli(ctx, repo_home):383 ctx.obj = ctx.with_resource(Repo(repo_home))384385@cli.command()386@click.pass_obj387def log(obj):388 # obj is the repo opened in the cli group389 for entry in obj.db.query(...):390 click.echo(entry)391```392393If the resource isn't a context manager, usually it can be wrapped in394one using something from {mod}`contextlib`. If that's not possible, use395the context's {meth}`~click.Context.call_on_close` method to register a396cleanup function.397398```python399@click.group()400@click.option("--name", default="repo.db")401@click.pass_context402def cli(ctx, repo_home):403 ctx.obj = db = open_db(repo_home)404405 @ctx.call_on_close406 def close_db():407 db.record_use()408 db.save()409 db.close()410```411412```{versionchanged} 8.2413`Context.call_on_close` and context managers registered via `Context.with_resource`414will be closed when the CLI exits. These were previously not called on exit.415```
deleted:docs/advanced.rst-408 removed
1Advanced Patterns2=================34.. currentmodule:: click56In addition to common functionality, Click offers some advanced features.78.. contents::9 :depth: 110 :local:1112Callbacks and Eager Options13---------------------------1415Sometimes, you want a parameter to completely change the execution flow.16For instance, this is the case when you want to have a ``--version``17parameter that prints out the version and then exits the application.1819Note: an actual implementation of a ``--version`` parameter that is20reusable is available in Click as :func:`click.version_option`. The code21here is merely an example of how to implement such a flag.2223In such cases, you need two concepts: eager parameters and a callback. An24eager parameter is a parameter that is handled before others, and a25callback is what executes after the parameter is handled. The eagerness26is necessary so that an earlier required parameter does not produce an27error message. For instance, if ``--version`` was not eager and a28parameter ``--foo`` was required and defined before, you would need to29specify it for ``--version`` to work. For more information, see30:ref:`callback-evaluation-order`.3132A callback is a function that is invoked with three parameters: the33current :class:`Context`, the current :class:`Parameter`, and the value.34The context provides some useful features such as quitting the35application and gives access to other already processed parameters.3637Here's an example for a ``--version`` flag:3839.. click:example::4041 def print_version(ctx, param, value):42 if not value or ctx.resilient_parsing:43 return44 click.echo('Version 1.0')45 ctx.exit()4647 @click.command()48 @click.option('--version', is_flag=True, callback=print_version,49 expose_value=False, is_eager=True)50 def hello():51 click.echo('Hello World!')5253The `expose_value` parameter prevents the pretty pointless ``version``54parameter from being passed to the callback. If that was not specified, a55boolean would be passed to the `hello` script. The `resilient_parsing`56flag is applied to the context if Click wants to parse the command line57without any destructive behavior that would change the execution flow. In58this case, because we would exit the program, we instead do nothing.5960What it looks like:6162.. click:run::6364 invoke(hello)65 invoke(hello, args=['--version'])6667Callbacks for Validation68------------------------6970.. versionchanged:: 2.07172If you want to apply custom validation logic, you can do this in the73parameter callbacks. These callbacks can both modify values as well as74raise errors if the validation does not work. The callback runs after75type conversion. It is called for all sources, including prompts.7677In Click 1.0, you can only raise the :exc:`UsageError` but starting with78Click 2.0, you can also raise the :exc:`BadParameter` error, which has the79added advantage that it will automatically format the error message to80also contain the parameter name.8182.. click:example::8384 def validate_rolls(ctx, param, value):85 if isinstance(value, tuple):86 return value8788 try:89 rolls, _, dice = value.partition("d")90 return int(dice), int(rolls)91 except ValueError:92 raise click.BadParameter("format must be 'NdM'")9394 @click.command()95 @click.option(96 "--rolls", type=click.UNPROCESSED, callback=validate_rolls,97 default="1d6", prompt=True,98 )99 def roll(rolls):100 sides, times = rolls101 click.echo(f"Rolling a {sides}-sided dice {times} time(s)")102103.. click:run::104105 invoke(roll, args=["--rolls=42"])106 println()107 invoke(roll, args=["--rolls=2d12"])108 println()109 invoke(roll, input=["42", "2d12"])110111Parameter Modifications112-----------------------113114Parameters (options and arguments) are forwarded to the command callbacks115as you have seen. One common way to prevent a parameter from being passed116to the callback is the `expose_value` argument to a parameter which hides117the parameter entirely. The way this works is that the :class:`Context`118object has a :attr:`~Context.params` attribute which is a dictionary of119all parameters. Whatever is in that dictionary is being passed to the120callbacks.121122This can be used to make up additional parameters. Generally this pattern123is not recommended but in some cases it can be useful. At the very least124it's good to know that the system works this way.125126.. click:example::127128 import urllib129130 def open_url(ctx, param, value):131 if value is not None:132 ctx.params['fp'] = urllib.urlopen(value)133 return value134135 @click.command()136 @click.option('--url', callback=open_url)137 def cli(url, fp=None):138 if fp is not None:139 click.echo(f"{url}: {fp.code}")140141In this case the callback returns the URL unchanged but also passes a142second ``fp`` value to the callback. What's more recommended is to pass143the information in a wrapper however:144145.. click:example::146147 import urllib148149 class URL(object):150151 def __init__(self, url, fp):152 self.url = url153 self.fp = fp154155 def open_url(ctx, param, value):156 if value is not None:157 return URL(value, urllib.urlopen(value))158159 @click.command()160 @click.option('--url', callback=open_url)161 def cli(url):162 if url is not None:163 click.echo(f"{url.url}: {url.fp.code}")164165166Token Normalization167-------------------168169.. versionadded:: 2.0170171Starting with Click 2.0, it's possible to provide a function that is used172for normalizing tokens. Tokens are option names, choice values, or command173values. This can be used to implement case insensitive options, for174instance.175176In order to use this feature, the context needs to be passed a function that177performs the normalization of the token. For instance, you could have a178function that converts the token to lowercase:179180.. click:example::181182 CONTEXT_SETTINGS = dict(token_normalize_func=lambda x: x.lower())183184 @click.command(context_settings=CONTEXT_SETTINGS)185 @click.option('--name', default='Pete')186 def cli(name):187 click.echo(f"Name: {name}")188189And how it works on the command line:190191.. click:run::192193 invoke(cli, prog_name='cli', args=['--NAME=Pete'])194195Invoking Other Commands196-----------------------197198Sometimes, it might be interesting to invoke one command from another199command. This is a pattern that is generally discouraged with Click, but200possible nonetheless. For this, you can use the :func:`Context.invoke`201or :func:`Context.forward` methods.202203They work similarly, but the difference is that :func:`Context.invoke` merely204invokes another command with the arguments you provide as a caller,205whereas :func:`Context.forward` fills in the arguments from the current206command. Both accept the command as the first argument and everything else207is passed onwards as you would expect.208209Example:210211.. click:example::212213 cli = click.Group()214215 @cli.command()216 @click.option('--count', default=1)217 def test(count):218 click.echo(f'Count: {count}')219220 @cli.command()221 @click.option('--count', default=1)222 @click.pass_context223 def dist(ctx, count):224 ctx.forward(test)225 ctx.invoke(test, count=42)226227And what it looks like:228229.. click:run::230231 invoke(cli, prog_name='cli', args=['dist'])232233234235.. _forwarding-unknown-options:236237Forwarding Unknown Options238--------------------------239240In some situations it is interesting to be able to accept all unknown241options for further manual processing. Click can generally do that as of242Click 4.0, but it has some limitations that lie in the nature of the243problem. The support for this is provided through a parser flag called244``ignore_unknown_options`` which will instruct the parser to collect all245unknown options and to put them to the leftover argument instead of246triggering a parsing error.247248This can generally be activated in two different ways:2492501. It can be enabled on custom :class:`Command` subclasses by changing251 the :attr:`~Command.ignore_unknown_options` attribute.2522. It can be enabled by changing the attribute of the same name on the253 context class (:attr:`Context.ignore_unknown_options`). This is best254 changed through the ``context_settings`` dictionary on the command.255256For most situations the easiest solution is the second. Once the behavior257is changed something needs to pick up those leftover options (which at258this point are considered arguments). For this again you have two259options:2602611. You can use :func:`pass_context` to get the context passed. This will262 only work if in addition to :attr:`~Context.ignore_unknown_options`263 you also set :attr:`~Context.allow_extra_args` as otherwise the264 command will abort with an error that there are leftover arguments.265 If you go with this solution, the extra arguments will be collected in266 :attr:`Context.args`.2672. You can attach an :func:`argument` with ``nargs`` set to `-1` which268 will eat up all leftover arguments. In this case it's recommended to269 set the `type` to :data:`UNPROCESSED` to avoid any string processing270 on those arguments as otherwise they are forced into unicode strings271 automatically which is often not what you want.272273In the end you end up with something like this:274275.. click:example::276277 import sys278 from subprocess import call279280 @click.command(context_settings=dict(281 ignore_unknown_options=True,282 ))283 @click.option('-v', '--verbose', is_flag=True, help='Enables verbose mode')284 @click.argument('timeit_args', nargs=-1, type=click.UNPROCESSED)285 def cli(verbose, timeit_args):286 """A fake wrapper around Python's timeit."""287 cmdline = ['echo', 'python', '-mtimeit'] + list(timeit_args)288 if verbose:289 click.echo(f"Invoking: {' '.join(cmdline)}")290 call(cmdline)291292And what it looks like:293294.. click:run::295296 invoke(cli, prog_name='cli', args=['--help'])297 println()298 invoke(cli, prog_name='cli', args=['-n', '100', 'a = 1; b = 2; a * b'])299 println()300 invoke(cli, prog_name='cli', args=['-v', 'a = 1; b = 2; a * b'])301302As you can see the verbosity flag is handled by Click, everything else303ends up in the `timeit_args` variable for further processing which then304for instance, allows invoking a subprocess. There are a few things that305are important to know about how this ignoring of unhandled flag happens:306307* Unknown long options are generally ignored and not processed at all.308 So for instance if ``--foo=bar`` or ``--foo bar`` are passed they309 generally end up like that. Note that because the parser cannot know310 if an option will accept an argument or not, the ``bar`` part might be311 handled as an argument.312* Unknown short options might be partially handled and reassembled if313 necessary. For instance in the above example there is an option314 called ``-v`` which enables verbose mode. If the command would be315 ignored with ``-va`` then the ``-v`` part would be handled by Click316 (as it is known) and ``-a`` would end up in the leftover parameters317 for further processing.318* Depending on what you plan on doing you might have some success by319 disabling interspersed arguments320 (:attr:`~Context.allow_interspersed_args`) which instructs the parser321 to not allow arguments and options to be mixed. Depending on your322 situation this might improve your results.323324Generally though the combined handling of options and arguments from325your own commands and commands from another application are discouraged326and if you can avoid it, you should. It's a much better idea to have327everything below a subcommand be forwarded to another application than to328handle some arguments yourself.329330331Managing Resources332------------------333334It can be useful to open a resource in a group, to be made available to335subcommands. Many types of resources need to be closed or otherwise336cleaned up after use. The standard way to do this in Python is by using337a context manager with the ``with`` statement.338339For example, the ``Repo`` class from :doc:`complex` might actually be340defined as a context manager:341342.. code-block:: python343344 class Repo:345 def __init__(self, home=None):346 self.home = os.path.abspath(home or ".")347 self.db = None348349 def __enter__(self):350 path = os.path.join(self.home, "repo.db")351 self.db = open_database(path)352 return self353354 def __exit__(self, exc_type, exc_value, tb):355 self.db.close()356357Ordinarily, it would be used with the ``with`` statement:358359.. code-block:: python360361 with Repo() as repo:362 repo.db.query(...)363364However, a ``with`` block in a group would exit and close the database365before it could be used by a subcommand.366367Instead, use the context's :meth:`~click.Context.with_resource` method368to enter the context manager and return the resource. When the group and369any subcommands finish, the context's resources are cleaned up.370371.. code-block:: python372373 @click.group()374 @click.option("--repo-home", default=".repo")375 @click.pass_context376 def cli(ctx, repo_home):377 ctx.obj = ctx.with_resource(Repo(repo_home))378379 @cli.command()380 @click.pass_obj381 def log(obj):382 # obj is the repo opened in the cli group383 for entry in obj.db.query(...):384 click.echo(entry)385386If the resource isn't a context manager, usually it can be wrapped in387one using something from :mod:`contextlib`. If that's not possible, use388the context's :meth:`~click.Context.call_on_close` method to register a389cleanup function.390391.. code-block:: python392393 @click.group()394 @click.option("--name", default="repo.db")395 @click.pass_context396 def cli(ctx, repo_home):397 ctx.obj = db = open_db(repo_home)398399 @ctx.call_on_close400 def close_db():401 db.record_use()402 db.save()403 db.close()404405406.. versionchanged:: 8.2 ``Context.call_on_close`` and context managers registered407 via ``Context.with_resource`` will be closed when the CLI exits. These were408 previously not called on exit.
added:docs/option-decorators.md+86 added
1# Options Shortcut Decorators23```{currentmodule} click4```56For convenience commonly used combinations of options arguments are available as their own decorators.78```{contents}9---10depth: 211local: true12---13```1415## Password Option1617Click supports hidden prompts and asking for confirmation. This is useful for password input:1819```{eval-rst}20.. click:example::2122 import codecs2324 @click.command()25 @click.option(26 "--password", prompt=True, hide_input=True,27 confirmation_prompt=True28 )29 def encode(password):30 click.echo(f"encoded: {codecs.encode(password, 'rot13')}")3132.. click:run::3334 invoke(encode, input=['secret', 'secret'])35```3637Because this combination of parameters is quite common, this can also be38replaced with the {func}`password_option` decorator:3940```python41 @click.command()42 @click.password_option()43 def encrypt(password):44 click.echo(f"encoded: to {codecs.encode(password, 'rot13')}")45```4647## Confirmation Option4849For dangerous operations, it's very useful to be able to ask a user for confirmation. This can be done by adding a50boolean `--yes` flag and asking for confirmation if the user did not provide it and to fail in a callback:5152```{eval-rst}53.. click:example::5455 def abort_if_false(ctx, param, value):56 if not value:57 ctx.abort()5859 @click.command()60 @click.option('--yes', is_flag=True, callback=abort_if_false,61 expose_value=False,62 prompt='Are you sure you want to drop the db?')63 def dropdb():64 click.echo('Dropped all tables!')6566And what it looks like on the command line:6768.. click:run::6970 invoke(dropdb, input=['n'])71 invoke(dropdb, args=['--yes'])7273Because this combination of parameters is quite common, this can also be74replaced with the :func:`confirmation_option` decorator:7576.. click:example::7778 @click.command()79 @click.confirmation_option(prompt='Are you sure you want to drop the db?')80 def dropdb():81 click.echo('Dropped all tables!')82```8384## Version Option8586{func}`version_option` adds a `--version` option which immediately prints the version number and exits the program.
deleted:docs/option-decorators.rst-84 removed
1Options Shortcut Decorators2===========================34.. currentmodule:: click56For convenience commonly used combinations of options arguments are available as their own decorators.78.. contents::9 :depth: 210 :local:1112Password Option13------------------1415Click supports hidden prompts and asking for confirmation. This is16useful for password input:1718.. click:example::1920 import codecs2122 @click.command()23 @click.option(24 "--password", prompt=True, hide_input=True,25 confirmation_prompt=True26 )27 def encode(password):28 click.echo(f"encoded: {codecs.encode(password, 'rot13')}")2930.. click:run::3132 invoke(encode, input=['secret', 'secret'])3334Because this combination of parameters is quite common, this can also be35replaced with the :func:`password_option` decorator:3637.. code-block:: python3839 @click.command()40 @click.password_option()41 def encrypt(password):42 click.echo(f"encoded: to {codecs.encode(password, 'rot13')}")4344Confirmation Option45--------------------4647For dangerous operations, it's very useful to be able to ask a user for48confirmation. This can be done by adding a boolean ``--yes`` flag and49asking for confirmation if the user did not provide it and to fail in a50callback:5152.. click:example::5354 def abort_if_false(ctx, param, value):55 if not value:56 ctx.abort()5758 @click.command()59 @click.option('--yes', is_flag=True, callback=abort_if_false,60 expose_value=False,61 prompt='Are you sure you want to drop the db?')62 def dropdb():63 click.echo('Dropped all tables!')6465And what it looks like on the command line:6667.. click:run::6869 invoke(dropdb, input=['n'])70 invoke(dropdb, args=['--yes'])7172Because this combination of parameters is quite common, this can also be73replaced with the :func:`confirmation_option` decorator:7475.. click:example::7677 @click.command()78 @click.confirmation_option(prompt='Are you sure you want to drop the db?')79 def dropdb():80 click.echo('Dropped all tables!')8182Version Option83----------------84:func:`version_option` adds a ``--version`` option which immediately prints the version number and exits the program.
modified:docs/options.md+5 added-3 removed
129 unmodified lines
130```131132## Multi Value Options133134To 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.134To make an option take multiple values, pass in `nargs`. Note you may pass in any positive integer, but not -1. The values are passed to the underlying function as a tuple.135136```{eval-rst}137.. click:example::138
55 unmodified lines
194(multiple-options)=195196## Multiple Options197198The 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.198The multiple options format allows options to take an arbitrary number of arguments (which is called variadic). The arguments are passed to the underlying function as a tuple. If set, the default must be a list or tuple. Setting a string as a default will be interpreted as list of characters.199200```{eval-rst}201.. click:example::202203 @click.command()204 @click.option('--message', '-m', multiple=True)205 def commit(message):206 click.echo('\n'.join(message))206 click.echo(message)207 for m in message:208 click.echo(m)209210.. click:run::211212 invoke(commit, args=['-m', 'foo', '-m', 'bar', '-m', 'here'])
287 unmodified lines
modified:src/click/_termui_impl.py+1 added-1 removed
448 unmodified lines
449 color = True450451 c = subprocess.Popen(452 [str(cmd_path)] + cmd_params,453 shell=True,453 shell=False,454 stdin=subprocess.PIPE,455 env=env,456 errors="replace",457 text=True,
390 unmodified lines
modified:src/click/core.py+26 added-6 removed
797 unmodified lines
798 ctx = self._make_sub_context(other_cmd)799800 for param in other_cmd.params:801 if param.name not in kwargs and param.expose_value:802 default_value = param.get_default(ctx)803 # We explicitly hide the :attr:`UNSET` value to the user, as we804 # choose to make it an implementation detail. And because ``invoke``805 # has been designed as part of Click public API, we return ``None``806 # instead. Refs:807 # https://github.com/pallets/click/issues/3066808 # https://github.com/pallets/click/issues/3065809 # https://github.com/pallets/click/pull/3068810 if default_value is UNSET:811 default_value = None812 kwargs[param.name] = param.type_cast_value( # type: ignore803 ctx, param.get_default(ctx)813 ctx, default_value814 )815816 # Track all kwargs as params, so that forward() will pass817 # them on in subsequent calls.
407 unmodified lines
12251226 for param in iter_params_for_processing(param_order, self.get_params(ctx)):1227 _, args = param.handle_parse_result(ctx, opts, args)12281229 # We now have all parameters' values into `ctx.params`, but the data may contain1230 # the `UNSET` sentinel.1231 # Convert `UNSET` to `None` to ensure that the user doesn't see `UNSET`.1232 #1233 # Waiting until after the initial parse to convert allows us to treat `UNSET`1234 # more like a missing value when multiple params use the same name.1235 # Refs:1236 # https://github.com/pallets/click/issues/30711237 # https://github.com/pallets/click/pull/30791238 for name, value in ctx.params.items():1239 if value is UNSET:1240 ctx.params[name] = None12411242 if args and not ctx.allow_extra_args and not ctx.resilient_parsing:1243 ctx.fail(1244 ngettext(1245 "Got unexpected extra argument ({args})",
1304 unmodified lines
2550 self.expose_value2551 # We skip adding the value if it was previously set by another parameter2552 # targeting the same variable name. This prevents parameters competing for2553 # the same name to override each other.2531 and self.name not in ctx.params2554 and (self.name not in ctx.params or ctx.params[self.name] is UNSET)2555 ):2556 # Click is logically enforcing that the name is None if the parameter is2557 # not to be exposed. We still assert it here to please the type checker.2558 assert self.name is not None, (2559 f"{self!r} parameter's name should not be None when exposing value."2560 )2538 # Normalize UNSET values to None, as we're about to pass them to the2539 # command function and move them to the pure-Python realm of user-written2540 # code.2541 ctx.params[self.name] = value if value is not UNSET else None2561 ctx.params[self.name] = value25622563 return value, args25642565 def get_help_record(self, ctx: Context) -> tuple[str, str] | None:
802 unmodified lines
modified:tests/test_commands.py+37 added-9 removed
226 unmodified lines
227 assert result.exception is None228 assert result.output == "Debug is off\n"229230231@pytest.mark.parametrize(232 ("opt_params", "expected"),233 (234 # Original tests.235 ({"type": click.INT, "default": 42}, 42),236 ({"type": click.INT, "default": "15"}, 15),237 ({"multiple": True}, ()),238 # SENTINEL value tests.239 ({"default": None}, None),240 ({"type": click.STRING}, None), # No default specified, should be None.241 ({"type": click.BOOL, "default": False}, False),242 ({"type": click.BOOL, "default": True}, True),243 ({"type": click.FLOAT, "default": 3.14}, 3.14),244 # Multiple with default.245 ({"multiple": True, "default": [1, 2, 3]}, (1, 2, 3)),246 ({"multiple": True, "default": ()}, ()),247 # Required option without value should use SENTINEL behavior.248 ({"required": False}, None),249 # Choice type with default.250 ({"type": click.Choice(["a", "b", "c"]), "default": "b"}, "b"),251 # Path type with default.252 ({"type": click.Path(), "default": "/tmp"}, "/tmp"),253 # Flag options.254 ({"is_flag": True, "default": False}, False),255 ({"is_flag": True, "default": True}, True),256 # Count option.257 ({"count": True}, 0),258 # Hidden option.259 ({"hidden": True, "default": "secret"}, "secret"),260 ),261)231def test_other_command_invoke_with_defaults(runner):262def test_other_command_invoke_with_defaults(runner, opt_params, expected):263 @click.command()264 @click.pass_context265 def cli(ctx):266 return ctx.invoke(other_cmd)267268 @click.command()238 @click.option("-a", type=click.INT, default=42)239 @click.option("-b", type=click.INT, default="15")240 @click.option("-c", multiple=True)269 @click.option("-a", **opt_params)270 @click.pass_context242 def other_cmd(ctx, a, b, c):243 return ctx.info_name, a, b, c271 def other_cmd(ctx, a):272 return ctx.info_name, a273274 result = runner.invoke(cli, standalone_mode=False)246 # invoke should type cast default values, str becomes int, empty247 # multiple should be empty tuple instead of None248 assert result.return_value == ("other", 42, 15, ())275276 assert result.return_value == ("other", expected)277278279def test_invoked_subcommand(runner):280 @click.group(invoke_without_command=True)281 @click.pass_context282 def cli(ctx):
293 unmodified lines
modified:tests/test_defaults.py+26 added
82 unmodified lines
83 assert "True" in result.output8485 result = runner.invoke(cli, ["foo", "--help"], default_map={"foo": {"name": True}})86 assert "default: name" in result.output878889def test_shared_param_prefers_first_default(runner):90 """test that the first default is chosen when multiple flags share a param name"""9192 @click.command93 @click.option("--red", "color", flag_value="red")94 @click.option("--green", "color", flag_value="green", default=True)95 def prefers_green(color):96 click.echo(color)9798 @click.command99 @click.option("--red", "color", flag_value="red", default=True)100 @click.option("--green", "color", flag_value="green")101 def prefers_red(color):102 click.echo(color)103104 result = runner.invoke(prefers_green, [])105 assert "green" in result.output106 result = runner.invoke(prefers_green, ["--red"])107 assert "red" in result.output108109 result = runner.invoke(prefers_red, [])110 assert "red" in result.output111 result = runner.invoke(prefers_red, ["--green"])112 assert "green" in result.output
modified:CHANGES.rst+14 added-3 removed
1.. currentmodule:: click23Version 8.3.x4--------------56Unreleased78- Don't discard pager arguments by correctly using ``subprocess.Popen``. :issue:`3039`9 :pr:`3055`10- Replace ``Sentinel.UNSET`` default values by ``None`` as they're passed through11 the ``Context.invoke()`` method. :issue:`3066` :issue:`3065` :pr:`3068`12- Fix conversion of ``Sentinel.UNSET`` happening too early, which caused incorrect13 behavior for multiple parameters using the same name. :issue:`3071` :pr:`3079`1415Version 8.3.016--------------176Released 2025-09-1518Released 2025-09-171920- **Improved flag option handling**: Reworked the relationship between ``flag_value``21 and ``default`` parameters for better consistency:22
7 unmodified lines
30- Allow ``default`` to be set on ``Argument`` for ``nargs = -1``. :issue:`2164`31 :pr:`3030`32- Show correct auto complete value for ``nargs`` option in combination with flag33 option :issue:`2813`22- Show correct auto complete value for nargs option in combination with flag option :issue:`2813`34- Fix handling of quoted and escaped parameters in Fish autocompletion. :issue:`2995` :pr:`3013`35- Lazily import ``shutil``. :pr:`3023`36- Properly forward exception information to resources registered with37 ``click.core.Context.with_resource()``. :issue:`2447` :pr:`3058`27- Fix regression related to EOF handling in CliRunner. :issue:`2939`:pr:`2940`38- Fix regression related to EOF handling in ``CliRunner``. :issue:`2939` :pr:`2940`3940Version 8.2.241-------------42
1262 unmodified lines
modified:pyproject.toml+2 added-2 removed
1[project]2name = "click"3version = "8.3.0"3version = "8.3.dev"4description = "Composable command line interface toolkit"5readme = "README.md"6license = "BSD-3-Clause"7license-files = ["LICENSE.txt"]
49 unmodified lines
57 "pytest",58]5960[build-system]61requires = ["flit_core<4"]61requires = ["flit_core>=3.11,<4"]62build-backend = "flit_core.buildapi"6364[tool.flit.module]65name = "click"
143 unmodified lines
modified:uv.lock+1 added-1 removed
137 unmodified lines
138]139140[[package]]141name = "click"142version = "8.3.0"142version = "8.3.dev0"143source = { editable = "." }144dependencies = [145 { name = "colorama", marker = "sys_platform == 'win32'" },146]
1076 unmodified lines