Merge branch 'stable' into pager-process-without-shell
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Rowlando13 · committed by GitHub · parents 7db1f20, 35e6a78 · Browse files · 9 files·+700 added−679 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
9 files+700 added−679 removed
- other:+700 added−679 removed
Provenance
- Commit
3f5eea3- Tree
3670a7f- Author
Rowlando13 <67291205+Rowlando13@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent 1
7db1f20- Parent 2
35e6a78
9 files changed+700 added−679 removed
added:docs/advanced.md+415 added
1+# Advanced Patterns2+3+```{currentmodule} click4+```5+6+In addition to common functionality, Click offers some advanced features.7+8+```{contents}9+:depth: 110+:local: true11+```12+13+## Callbacks and Eager Options14+15+Sometimes, you want a parameter to completely change the execution flow.16+For instance, this is the case when you want to have a `--version`17+parameter that prints out the version and then exits the application.18+19+Note: an actual implementation of a `--version` parameter that is20+reusable is available in Click as {func}`click.version_option`. The code21+here is merely an example of how to implement such a flag.22+23+In such cases, you need two concepts: eager parameters and a callback. An24+eager parameter is a parameter handled before others, and a25+callback is what executes after the parameter is handled. The eagerness26+is necessary so that an earlier required parameter does not produce an27+error message. For instance, if `--version` was not eager and a28+parameter `--foo` was required and defined before, you would need to29+specify it for `--version` to work. For more information, see30+{ref}`callback-evaluation-order`.31+32+A callback is a function invoked with three parameters: the33+current {class}`Context`, the current {class}`Parameter`, and the value.34+The context provides some useful features such as quitting the35+application and gives access to other already processed parameters.36+37+Here's an example for a `--version` flag:38+39+```{eval-rst}40+.. click:example::41+42+ def print_version(ctx, param, value):43+ if not value or ctx.resilient_parsing:44+ return45+ click.echo('Version 1.0')46+ ctx.exit()47+48+ @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!')53+54+55+What it looks like:56+57+58+.. click:run::59+60+ invoke(hello)61+ invoke(hello, args=['--version'])62+```63+The `expose_value` parameter prevents the pretty pointless `version`64+parameter from being passed to the callback. If that was not specified, a65+boolean would be passed to the `hello` script. The `resilient_parsing`66+flag is applied to the context if Click wants to parse the command line67+without any destructive behavior that would change the execution flow. In68+this case, because we would exit the program, we instead do nothing.69+70+## Callbacks for Validation71+72+```{versionchanged} 2.073+```74+75+If you want to apply custom validation logic, you can do this in the76+parameter callbacks. These callbacks can both modify values and77+raise errors if the validation does not work. The callback runs after78+type conversion. It is called for all sources, including prompts.79+80+In Click 1.0, you can only raise the {exc}`UsageError` but starting with81+Click 2.0, you can also raise the {exc}`BadParameter` error, which has the82+added advantage that it will automatically format the error message to83+also contain the parameter name.84+85+```{eval-rst}86+.. click:example::87+88+ def validate_rolls(ctx, param, value):89+ if isinstance(value, tuple):90+ return value91+92+ try:93+ rolls, _, dice = value.partition("d")94+ return int(dice), int(rolls)95+ except ValueError:96+ raise click.BadParameter("format must be 'NdM'")97+98+ @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)")106+107+.. click:run::108+109+ invoke(roll, args=["--rolls=42"])110+ println()111+ invoke(roll, args=["--rolls=2d12"])112+ println()113+ invoke(roll, input=["42", "2d12"])114+```115+116+## Parameter Modifications117+118+Parameters (options and arguments) are forwarded to the command callbacks,119+as you have seen. One common way to prevent a parameter from being passed120+to the callback is the `expose_value` argument to a parameter which hides121+the parameter entirely. The way this works is that the {class}`Context`122+object has a {attr}`~Context.params` attribute which is a dictionary of123+all parameters. Whatever is in that dictionary is being passed to the124+callbacks.125+126+This can be used to make up additional parameters. Generally, this pattern127+is not recommended, but in some cases it can be useful. At the very least,128+it's good to know that the system works this way.129+130+```{eval-rst}131+.. click:example::132+133+ import urllib134+135+ def open_url(ctx, param, value):136+ if value is not None:137+ ctx.params['fp'] = urllib.urlopen(value)138+ return value139+140+ @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}")145+146+In this case the callback returns the URL unchanged but also passes a147+second `fp` value to the callback. What's more recommended is to pass148+the information in a wrapper, however:149+150+.. click:example::151+152+ import urllib153+154+ class URL(object):155+156+ def __init__(self, url, fp):157+ self.url = url158+ self.fp = fp159+160+ def open_url(ctx, param, value):161+ if value is not None:162+ return URL(value, urllib.urlopen(value))163+164+ @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}")169+170+```171+172+## Token Normalization173+174+```{versionadded} 2.0175+```176+177+Starting with Click 2.0, it's possible to provide a function used178+for normalizing tokens. Tokens are option names, choice values, or command179+values. This can be used to implement case-insensitive options, for180+instance.181+182+To use this feature, the context needs to be passed a function that183+performs the normalization of the token. Such as a function that converts the184+token to lowercase:185+186+```{eval-rst}187+.. click:example::188+189+ CONTEXT_SETTINGS = dict(token_normalize_func=lambda x: x.lower())190+191+ @click.command(context_settings=CONTEXT_SETTINGS)192+ @click.option('--name', default='Pete')193+ def cli(name):194+ click.echo(f"Name: {name}")195+196+# And how it works on the command line:197+198+.. click:run::199+200+ invoke(cli, prog_name='cli', args=['--NAME=Pete'])201+```202+203+## Invoking Other Commands204+205+Sometimes, it might be interesting to invoke one command from another206+command. This is a pattern generally discouraged with Click, but207+possible nonetheless. For this, you can use the {func}`Context.invoke`208+or {func}`Context.forward` methods.209+210+They work similarly, but the difference is that {func}`Context.invoke` merely211+invokes another command with the arguments you provide as a caller,212+whereas {func}`Context.forward` fills in the arguments from the current213+command. Both accept the command as the first argument, and everything else214+is passed onwards as you would expect.215+216+Example:217+218+```{eval-rst}219+.. click:example::220+221+ cli = click.Group()222+223+ @cli.command()224+ @click.option('--count', default=1)225+ def test(count):226+ click.echo(f'Count: {count}')227+228+ @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)234+235+And what it looks like:236+237+.. click:run::238+239+ invoke(cli, prog_name='cli', args=['dist'])240+```241+242+(forwarding-unknown-options)=243+244+## Forwarding Unknown Options245+246+In some situations, it is interesting to be able to accept all unknown247+options for further manual processing. Click can generally do that as of248+Click 4.0, but it has some limitations that lie in the nature of the249+problem. The support for this is provided through a parser flag called250+`ignore_unknown_options` which will instruct the parser to collect all251+unknown options and to put them to the leftover argument instead of252+triggering a parsing error.253+254+This can generally be activated in two different ways:255+256+1. It can be enabled on custom {class}`Command` subclasses by changing257+ the {attr}`~Command.ignore_unknown_options` attribute.258+2. 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.261+262+For most situations, the easiest solution is the second. Once the behavior263+is changed, something needs to pick up those leftover options (which at264+this point are considered arguments). For this again, you have two265+options:266+267+1. 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`.273+2. 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.278+279+In the end, the result looks something like this:280+281+```{eval-rst}282+.. click:example::283+284+ import sys285+ from subprocess import call286+287+ @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)298+299+300+And the final output resembles the following:301+302+.. click:run::303+304+ 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+```310+311+As you can see, Click handles the verbosity flag and everything else312+ends up in the `timeit_args` variable for further processing, which then313+for instance, allows invoking a subprocess. There are a few things that314+are important to know about how this ignoring of unhandled flag happens:315+316+- 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.332+333+Generally, combining the handling of options and arguments from your own334+commands with those from another application is discouraged, and you335+should avoid it if possible. It's a much better idea to have336+everything below a subcommand be forwarded to another application than to337+handle some arguments yourself.338+339+## Managing Resources340+341+It can be useful to open a resource in a group, to be made available to342+subcommands. Many types of resources need to be closed or otherwise343+cleaned up after use. The standard way to do this in Python is by using344+a context manager with the `with` statement.345+346+For example, the `Repo` class from {doc}`complex` might actually be347+defined as a context manager:348+349+```python350+class Repo:351+ def __init__(self, home=None):352+ self.home = os.path.abspath(home or ".")353+ self.db = None354+355+ def __enter__(self):356+ path = os.path.join(self.home, "repo.db")357+ self.db = open_database(path)358+ return self359+360+ def __exit__(self, exc_type, exc_value, tb):361+ self.db.close()362+```363+364+Ordinarily, it would be used with the `with` statement:365+366+```python367+with Repo() as repo:368+ repo.db.query(...)369+```370+371+However, a `with` block in a group would exit and close the database372+before it could be used by a subcommand.373+374+Instead, use the context's {meth}`~click.Context.with_resource` method375+to enter the context manager and return the resource. When the group and376+any subcommands finish, the context's resources are cleaned up.377+378+```python379+@click.group()380+@click.option("--repo-home", default=".repo")381+@click.pass_context382+def cli(ctx, repo_home):383+ ctx.obj = ctx.with_resource(Repo(repo_home))384+385+@cli.command()386+@click.pass_obj387+def log(obj):388+ # obj is the repo opened in the cli group389+ for entry in obj.db.query(...):390+ click.echo(entry)391+```392+393+If the resource isn't a context manager, usually it can be wrapped in394+one using something from {mod}`contextlib`. If that's not possible, use395+the context's {meth}`~click.Context.call_on_close` method to register a396+cleanup function.397+398+```python399+@click.group()400+@click.option("--name", default="repo.db")401+@click.pass_context402+def cli(ctx, repo_home):403+ ctx.obj = db = open_db(repo_home)404+405+ @ctx.call_on_close406+ def close_db():407+ db.record_use()408+ db.save()409+ db.close()410+```411+412+```{versionchanged} 8.2413+`Context.call_on_close` and context managers registered via `Context.with_resource`414+will be closed when the CLI exits. These were previously not called on exit.415+```deleted:docs/advanced.rst-408 removed
1-Advanced Patterns2-=================3-4-.. currentmodule:: click5-6-In addition to common functionality, Click offers some advanced features.7-8-.. contents::9- :depth: 110- :local:11-12-Callbacks and Eager Options13----------------------------14-15-Sometimes, you want a parameter to completely change the execution flow.16-For instance, this is the case when you want to have a ``--version``17-parameter that prints out the version and then exits the application.18-19-Note: an actual implementation of a ``--version`` parameter that is20-reusable is available in Click as :func:`click.version_option`. The code21-here is merely an example of how to implement such a flag.22-23-In such cases, you need two concepts: eager parameters and a callback. An24-eager parameter is a parameter that is handled before others, and a25-callback is what executes after the parameter is handled. The eagerness26-is necessary so that an earlier required parameter does not produce an27-error message. For instance, if ``--version`` was not eager and a28-parameter ``--foo`` was required and defined before, you would need to29-specify it for ``--version`` to work. For more information, see30-:ref:`callback-evaluation-order`.31-32-A callback is a function that is invoked with three parameters: the33-current :class:`Context`, the current :class:`Parameter`, and the value.34-The context provides some useful features such as quitting the35-application and gives access to other already processed parameters.36-37-Here's an example for a ``--version`` flag:38-39-.. click:example::40-41- def print_version(ctx, param, value):42- if not value or ctx.resilient_parsing:43- return44- click.echo('Version 1.0')45- ctx.exit()46-47- @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!')52-53-The `expose_value` parameter prevents the pretty pointless ``version``54-parameter from being passed to the callback. If that was not specified, a55-boolean would be passed to the `hello` script. The `resilient_parsing`56-flag is applied to the context if Click wants to parse the command line57-without any destructive behavior that would change the execution flow. In58-this case, because we would exit the program, we instead do nothing.59-60-What it looks like:61-62-.. click:run::63-64- invoke(hello)65- invoke(hello, args=['--version'])66-67-Callbacks for Validation68-------------------------69-70-.. versionchanged:: 2.071-72-If you want to apply custom validation logic, you can do this in the73-parameter callbacks. These callbacks can both modify values as well as74-raise errors if the validation does not work. The callback runs after75-type conversion. It is called for all sources, including prompts.76-77-In Click 1.0, you can only raise the :exc:`UsageError` but starting with78-Click 2.0, you can also raise the :exc:`BadParameter` error, which has the79-added advantage that it will automatically format the error message to80-also contain the parameter name.81-82-.. click:example::83-84- def validate_rolls(ctx, param, value):85- if isinstance(value, tuple):86- return value87-88- try:89- rolls, _, dice = value.partition("d")90- return int(dice), int(rolls)91- except ValueError:92- raise click.BadParameter("format must be 'NdM'")93-94- @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)")102-103-.. click:run::104-105- invoke(roll, args=["--rolls=42"])106- println()107- invoke(roll, args=["--rolls=2d12"])108- println()109- invoke(roll, input=["42", "2d12"])110-111-Parameter Modifications112------------------------113-114-Parameters (options and arguments) are forwarded to the command callbacks115-as you have seen. One common way to prevent a parameter from being passed116-to the callback is the `expose_value` argument to a parameter which hides117-the parameter entirely. The way this works is that the :class:`Context`118-object has a :attr:`~Context.params` attribute which is a dictionary of119-all parameters. Whatever is in that dictionary is being passed to the120-callbacks.121-122-This can be used to make up additional parameters. Generally this pattern123-is not recommended but in some cases it can be useful. At the very least124-it's good to know that the system works this way.125-126-.. click:example::127-128- import urllib129-130- def open_url(ctx, param, value):131- if value is not None:132- ctx.params['fp'] = urllib.urlopen(value)133- return value134-135- @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}")140-141-In this case the callback returns the URL unchanged but also passes a142-second ``fp`` value to the callback. What's more recommended is to pass143-the information in a wrapper however:144-145-.. click:example::146-147- import urllib148-149- class URL(object):150-151- def __init__(self, url, fp):152- self.url = url153- self.fp = fp154-155- def open_url(ctx, param, value):156- if value is not None:157- return URL(value, urllib.urlopen(value))158-159- @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}")164-165-166-Token Normalization167--------------------168-169-.. versionadded:: 2.0170-171-Starting with Click 2.0, it's possible to provide a function that is used172-for normalizing tokens. Tokens are option names, choice values, or command173-values. This can be used to implement case insensitive options, for174-instance.175-176-In order to use this feature, the context needs to be passed a function that177-performs the normalization of the token. For instance, you could have a178-function that converts the token to lowercase:179-180-.. click:example::181-182- CONTEXT_SETTINGS = dict(token_normalize_func=lambda x: x.lower())183-184- @click.command(context_settings=CONTEXT_SETTINGS)185- @click.option('--name', default='Pete')186- def cli(name):187- click.echo(f"Name: {name}")188-189-And how it works on the command line:190-191-.. click:run::192-193- invoke(cli, prog_name='cli', args=['--NAME=Pete'])194-195-Invoking Other Commands196------------------------197-198-Sometimes, it might be interesting to invoke one command from another199-command. This is a pattern that is generally discouraged with Click, but200-possible nonetheless. For this, you can use the :func:`Context.invoke`201-or :func:`Context.forward` methods.202-203-They work similarly, but the difference is that :func:`Context.invoke` merely204-invokes another command with the arguments you provide as a caller,205-whereas :func:`Context.forward` fills in the arguments from the current206-command. Both accept the command as the first argument and everything else207-is passed onwards as you would expect.208-209-Example:210-211-.. click:example::212-213- cli = click.Group()214-215- @cli.command()216- @click.option('--count', default=1)217- def test(count):218- click.echo(f'Count: {count}')219-220- @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)226-227-And what it looks like:228-229-.. click:run::230-231- invoke(cli, prog_name='cli', args=['dist'])232-233-234-235-.. _forwarding-unknown-options:236-237-Forwarding Unknown Options238---------------------------239-240-In some situations it is interesting to be able to accept all unknown241-options for further manual processing. Click can generally do that as of242-Click 4.0, but it has some limitations that lie in the nature of the243-problem. The support for this is provided through a parser flag called244-``ignore_unknown_options`` which will instruct the parser to collect all245-unknown options and to put them to the leftover argument instead of246-triggering a parsing error.247-248-This can generally be activated in two different ways:249-250-1. It can be enabled on custom :class:`Command` subclasses by changing251- the :attr:`~Command.ignore_unknown_options` attribute.252-2. 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.255-256-For most situations the easiest solution is the second. Once the behavior257-is changed something needs to pick up those leftover options (which at258-this point are considered arguments). For this again you have two259-options:260-261-1. 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`.267-2. 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.272-273-In the end you end up with something like this:274-275-.. click:example::276-277- import sys278- from subprocess import call279-280- @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)291-292-And what it looks like:293-294-.. click:run::295-296- 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'])301-302-As you can see the verbosity flag is handled by Click, everything else303-ends up in the `timeit_args` variable for further processing which then304-for instance, allows invoking a subprocess. There are a few things that305-are important to know about how this ignoring of unhandled flag happens:306-307-* 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.323-324-Generally though the combined handling of options and arguments from325-your own commands and commands from another application are discouraged326-and if you can avoid it, you should. It's a much better idea to have327-everything below a subcommand be forwarded to another application than to328-handle some arguments yourself.329-330-331-Managing Resources332-------------------333-334-It can be useful to open a resource in a group, to be made available to335-subcommands. Many types of resources need to be closed or otherwise336-cleaned up after use. The standard way to do this in Python is by using337-a context manager with the ``with`` statement.338-339-For example, the ``Repo`` class from :doc:`complex` might actually be340-defined as a context manager:341-342-.. code-block:: python343-344- class Repo:345- def __init__(self, home=None):346- self.home = os.path.abspath(home or ".")347- self.db = None348-349- def __enter__(self):350- path = os.path.join(self.home, "repo.db")351- self.db = open_database(path)352- return self353-354- def __exit__(self, exc_type, exc_value, tb):355- self.db.close()356-357-Ordinarily, it would be used with the ``with`` statement:358-359-.. code-block:: python360-361- with Repo() as repo:362- repo.db.query(...)363-364-However, a ``with`` block in a group would exit and close the database365-before it could be used by a subcommand.366-367-Instead, use the context's :meth:`~click.Context.with_resource` method368-to enter the context manager and return the resource. When the group and369-any subcommands finish, the context's resources are cleaned up.370-371-.. code-block:: python372-373- @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))378-379- @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)385-386-If the resource isn't a context manager, usually it can be wrapped in387-one using something from :mod:`contextlib`. If that's not possible, use388-the context's :meth:`~click.Context.call_on_close` method to register a389-cleanup function.390-391-.. code-block:: python392-393- @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)398-399- @ctx.call_on_close400- def close_db():401- db.record_use()402- db.save()403- db.close()404-405-406-.. 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 Decorators2+3+```{currentmodule} click4+```5+6+For convenience commonly used combinations of options arguments are available as their own decorators.7+8+```{contents}9+---10+depth: 211+local: true12+---13+```14+15+## Password Option16+17+Click supports hidden prompts and asking for confirmation. This is useful for password input:18+19+```{eval-rst}20+.. click:example::21+22+ import codecs23+24+ @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')}")31+32+.. click:run::33+34+ invoke(encode, input=['secret', 'secret'])35+```36+37+Because this combination of parameters is quite common, this can also be38+replaced with the {func}`password_option` decorator:39+40+```python41+ @click.command()42+ @click.password_option()43+ def encrypt(password):44+ click.echo(f"encoded: to {codecs.encode(password, 'rot13')}")45+```46+47+## Confirmation Option48+49+For dangerous operations, it's very useful to be able to ask a user for confirmation. This can be done by adding a50+boolean `--yes` flag and asking for confirmation if the user did not provide it and to fail in a callback:51+52+```{eval-rst}53+.. click:example::54+55+ def abort_if_false(ctx, param, value):56+ if not value:57+ ctx.abort()58+59+ @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!')65+66+And what it looks like on the command line:67+68+.. click:run::69+70+ invoke(dropdb, input=['n'])71+ invoke(dropdb, args=['--yes'])72+73+Because this combination of parameters is quite common, this can also be74+replaced with the :func:`confirmation_option` decorator:75+76+.. click:example::77+78+ @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+```83+84+## Version Option85+86+{func}`version_option` adds a `--version` option which immediately prints the version number and exits the program.deleted:docs/option-decorators.rst-84 removed
1-Options Shortcut Decorators2-===========================3-4-.. currentmodule:: click5-6-For convenience commonly used combinations of options arguments are available as their own decorators.7-8-.. contents::9- :depth: 210- :local:11-12-Password Option13-------------------14-15-Click supports hidden prompts and asking for confirmation. This is16-useful for password input:17-18-.. click:example::19-20- import codecs21-22- @click.command()23- @click.option(24- "--password", prompt=True, hide_input=True,25- confirmation_prompt=True26- )27- def encode(password):28- click.echo(f"encoded: {codecs.encode(password, 'rot13')}")29-30-.. click:run::31-32- invoke(encode, input=['secret', 'secret'])33-34-Because this combination of parameters is quite common, this can also be35-replaced with the :func:`password_option` decorator:36-37-.. code-block:: python38-39- @click.command()40- @click.password_option()41- def encrypt(password):42- click.echo(f"encoded: to {codecs.encode(password, 'rot13')}")43-44-Confirmation Option45---------------------46-47-For dangerous operations, it's very useful to be able to ask a user for48-confirmation. This can be done by adding a boolean ``--yes`` flag and49-asking for confirmation if the user did not provide it and to fail in a50-callback:51-52-.. click:example::53-54- def abort_if_false(ctx, param, value):55- if not value:56- ctx.abort()57-58- @click.command()59- @click.option('--yes', is_flag=True, callback=abort_if_false,60- expose_value=False,61- prompt='Are you sure you want to drop the db?')62- def dropdb():63- click.echo('Dropped all tables!')64-65-And what it looks like on the command line:66-67-.. click:run::68-69- invoke(dropdb, input=['n'])70- invoke(dropdb, args=['--yes'])71-72-Because this combination of parameters is quite common, this can also be73-replaced with the :func:`confirmation_option` decorator:74-75-.. click:example::76-77- @click.command()78- @click.confirmation_option(prompt='Are you sure you want to drop the db?')79- def dropdb():80- click.echo('Dropped all tables!')81-82-Version Option83-----------------84-:func:`version_option` adds a ``--version`` option which immediately prints the version number and exits the program.added:docs/parameter-types.md+186 added
1+(parameter-types)=2+3+# Parameter Types4+5+```{currentmodule} click6+```7+8+When the parameter type is set using `type`, Click will leverage the type to make your life easier, for example adding9+data to your help pages. Most examples are done with options, but types are available to options and arguments.10+11+```{contents}12+---13+depth: 214+local: true15+---16+```17+18+## Built-in Types Examples19+20+(choice-opts)=21+22+### Choice23+24+Sometimes, you want to have a parameter be a choice of a list of values. In that case you can use {class}`Choice` type.25+It can be instantiated with a list of valid values. The originally passed choice will be returned, not the str passed on26+the command line. Token normalization functions and `case_sensitive=False` can cause the two to be different but still27+match. {meth}`Choice.normalize_choice` for more info.28+29+30+Example:31+32+```{eval-rst}33+.. click:example::34+35+ import enum36+37+ class HashType(enum.Enum):38+ MD5 = enum.auto()39+ SHA1 = enum.auto()40+41+ @click.command()42+ @click.option('--hash-type',43+ type=click.Choice(HashType, case_sensitive=False))44+ def digest(hash_type: HashType):45+ click.echo(hash_type)46+47+What it looks like:48+49+.. click:run::50+51+ invoke(digest, args=['--hash-type=MD5'])52+ println()53+ invoke(digest, args=['--hash-type=md5'])54+ println()55+ invoke(digest, args=['--hash-type=foo'])56+ println()57+ invoke(digest, args=['--help'])58+```59+60+Any iterable may be passed to {class}`Choice`. If an `Enum` is passed, the names of the enum members will be used as61+valid choices.62+63+Choices work with options that have `multiple=True`. If a `default` value is given with `multiple=True`, it should be a64+list or tuple of valid choices.65+66+Choices should be unique after normalization, see {meth}`Choice.normalize_choice` for more info.67+68+```{versionchanged} 7.169+The resulting value from an option will always be one of the originally passed choices70+regardless of `case_sensitive`.71+```72+73+(ranges)=74+75+### Int and Float Ranges76+77+The {class}`IntRange` type extends the {data}`INT` type to ensure the value is contained in the given range. The78+{class}`FloatRange` type does the same for {data}`FLOAT`.79+80+If `min` or `max` is omitted, that side is *unbounded*. Any value in that direction is accepted. By default, both bounds81+are *closed*, which means the boundary value is included in the accepted range. `min_open` and `max_open` can be used to82+exclude that boundary from the range.83+84+If `clamp` mode is enabled, a value that is outside the range is set to the boundary instead of failing. For example,85+the range `0, 5` would return `5` for the value `10`, or `0` for the value `-1`. When using {class}`FloatRange`, `clamp`86+can only be enabled if both bounds are *closed* (the default).87+88+```{eval-rst}89+.. click:example::90+91+ @click.command()92+ @click.option("--count", type=click.IntRange(0, 20, clamp=True))93+ @click.option("--digit", type=click.IntRange(0, 9))94+ def repeat(count, digit):95+ click.echo(str(digit) * count)96+97+.. click:run::98+99+ invoke(repeat, args=['--count=100', '--digit=5'])100+ invoke(repeat, args=['--count=6', '--digit=12'])101+```102+103+## Built-in Types Listing104+105+The supported parameter {ref}`click-api-types` are106+107+- `str` / {data}`click.STRING`: The default parameter type which indicates unicode strings.108+109+- `int` / {data}`click.INT`: A parameter that only accepts integers.110+111+- `float` / {data}`click.FLOAT`: A parameter that only accepts floating point values.112+113+- `bool` / {data}`click.BOOL`: A parameter that accepts boolean values. This is automatically used for boolean flags.114+ The string values "1", "true", "t", "yes", "y", and "on" convert to `True`. "0", "false", "f", "no", "n", and "off"115+ convert to `False`.116+117+- {data}`click.UUID`: A parameter that accepts UUID values. This is not automatically guessed but represented as118+ {class}`uuid.UUID`.119+120+```{eval-rst}121+* .. autoclass:: Choice122+ :noindex:123+```124+125+```{eval-rst}126+* .. autoclass:: DateTime127+ :noindex:128+```129+130+```{eval-rst}131+* .. autoclass:: File132+ :noindex:133+```134+135+```{eval-rst}136+* .. autoclass:: FloatRange137+ :noindex:138+```139+140+```{eval-rst}141+* .. autoclass:: IntRange142+ :noindex:143+```144+145+```{eval-rst}146+* .. autoclass:: Path147+ :noindex:148+```149+150+## How to Implement Custom Types151+152+To implement a custom type, you need to subclass the {class}`ParamType` class. For simple cases, passing a Python153+function that fails with a `ValueError` is also supported, though discouraged. Override the {meth}`~ParamType.convert`154+method to convert the value from a string to the correct type.155+156+The following code implements an integer type that accepts hex and octal numbers in addition to normal integers, and157+converts them into regular integers.158+159+```python160+import click161+162+class BasedIntParamType(click.ParamType):163+ name = "integer"164+165+ def convert(self, value, param, ctx):166+ if isinstance(value, int):167+ return value168+169+ try:170+ if value[:2].lower() == "0x":171+ return int(value[2:], 16)172+ elif value[:1] == "0":173+ return int(value, 8)174+ return int(value, 10)175+ except ValueError:176+ self.fail(f"{value!r} is not a valid integer", param, ctx)177+178+BASED_INT = BasedIntParamType()179+```180+181+The {attr}`~ParamType.name` attribute is optional and is used for documentation. Call {meth}`~ParamType.fail` if182+conversion fails. The `param` and `ctx` arguments may be `None` in some cases such as prompts.183+184+Values from user input or the command line will be strings, but default values and Python arguments may already be the185+correct type. The custom type should check at the top if the value is already valid and pass it through to support those186+cases.deleted:docs/parameter-types.rst-181 removed
1-.. _parameter-types:2-3-Parameter Types4-==================5-6-.. currentmodule:: click7-8-When the parameter type is set using ``type``, Click will leverage the type to make your life easier, for example adding data to your help pages. Most examples are done with options, but types are available to options and arguments.9-10-.. contents::11- :depth: 212- :local:13-14-Built-in Types Examples15-------------------------16-17-.. _choice-opts:18-19-Choice20-^^^^^^^^^^^^^^^^^^^^^^21-22-Sometimes, you want to have a parameter be a choice of a list of values.23-In that case you can use :class:`Choice` type. It can be instantiated24-with a list of valid values. The originally passed choice will be returned,25-not the str passed on the command line. Token normalization functions and26-``case_sensitive=False`` can cause the two to be different but still match.27-:meth:`Choice.normalize_choice` for more info.28-29-Example:30-31-.. click:example::32-33- import enum34-35- class HashType(enum.Enum):36- MD5 = enum.auto()37- SHA1 = enum.auto()38-39- @click.command()40- @click.option('--hash-type',41- type=click.Choice(HashType, case_sensitive=False))42- def digest(hash_type: HashType):43- click.echo(hash_type)44-45-What it looks like:46-47-.. click:run::48-49- invoke(digest, args=['--hash-type=MD5'])50- println()51- invoke(digest, args=['--hash-type=md5'])52- println()53- invoke(digest, args=['--hash-type=foo'])54- println()55- invoke(digest, args=['--help'])56-57-Any iterable may be passed to :class:`Choice`. If an ``Enum`` is passed, the58-names of the enum members will be used as valid choices.59-60-Choices work with options that have ``multiple=True``. If a ``default``61-value is given with ``multiple=True``, it should be a list or tuple of62-valid choices.63-64-Choices should be unique after normalization, see65-:meth:`Choice.normalize_choice` for more info.66-67-.. versionchanged:: 7.168- The resulting value from an option will always be one of the69- originally passed choices regardless of ``case_sensitive``.70-71-.. _ranges:72-73-Int and Float Ranges74-^^^^^^^^^^^^^^^^^^^^^^^75-76-The :class:`IntRange` type extends the :data:`INT` type to ensure the77-value is contained in the given range. The :class:`FloatRange` type does78-the same for :data:`FLOAT`.79-80-If ``min`` or ``max`` is omitted, that side is *unbounded*. Any value in81-that direction is accepted. By default, both bounds are *closed*, which82-means the boundary value is included in the accepted range. ``min_open``83-and ``max_open`` can be used to exclude that boundary from the range.84-85-If ``clamp`` mode is enabled, a value that is outside the range is set86-to the boundary instead of failing. For example, the range ``0, 5``87-would return ``5`` for the value ``10``, or ``0`` for the value ``-1``.88-When using :class:`FloatRange`, ``clamp`` can only be enabled if both89-bounds are *closed* (the default).90-91-.. click:example::92-93- @click.command()94- @click.option("--count", type=click.IntRange(0, 20, clamp=True))95- @click.option("--digit", type=click.IntRange(0, 9))96- def repeat(count, digit):97- click.echo(str(digit) * count)98-99-.. click:run::100-101- invoke(repeat, args=['--count=100', '--digit=5'])102- invoke(repeat, args=['--count=6', '--digit=12'])103-104-105-Built-in Types Listing106------------------------107-The supported parameter :ref:`click-api-types` are:108-109-* ``str`` / :data:`click.STRING`: The default parameter type which indicates unicode strings.110-111-* ``int`` / :data:`click.INT`: A parameter that only accepts integers.112-113-* ``float`` / :data:`click.FLOAT`: A parameter that only accepts floating point values.114-115-* ``bool`` / :data:`click.BOOL`: A parameter that accepts boolean values. This is automatically used116- for boolean flags. The string values "1", "true", "t", "yes", "y",117- and "on" convert to ``True``. "0", "false", "f", "no", "n", and118- "off" convert to ``False``.119-120-* :data:`click.UUID`:121- A parameter that accepts UUID values. This is not automatically122- guessed but represented as :class:`uuid.UUID`.123-124-* .. autoclass:: Choice125- :noindex:126-127-* .. autoclass:: DateTime128- :noindex:129-130-* .. autoclass:: File131- :noindex:132-133-* .. autoclass:: FloatRange134- :noindex:135-136-* .. autoclass:: IntRange137- :noindex:138-139-* .. autoclass:: Path140- :noindex:141-142-How to Implement Custom Types143--------------------------------144-145-To implement a custom type, you need to subclass the :class:`ParamType` class. For simple cases, passing a Python function that fails with a `ValueError` is also supported, though discouraged. Override the :meth:`~ParamType.convert` method to convert the value from a string to the correct type.146-147-The following code implements an integer type that accepts hex and octal148-numbers in addition to normal integers, and converts them into regular149-integers.150-151-.. code-block:: python152-153- import click154-155- class BasedIntParamType(click.ParamType):156- name = "integer"157-158- def convert(self, value, param, ctx):159- if isinstance(value, int):160- return value161-162- try:163- if value[:2].lower() == "0x":164- return int(value[2:], 16)165- elif value[:1] == "0":166- return int(value, 8)167- return int(value, 10)168- except ValueError:169- self.fail(f"{value!r} is not a valid integer", param, ctx)170-171- BASED_INT = BasedIntParamType()172-173-The :attr:`~ParamType.name` attribute is optional and is used for174-documentation. Call :meth:`~ParamType.fail` if conversion fails. The175-``param`` and ``ctx`` arguments may be ``None`` in some cases such as176-prompts.177-178-Values from user input or the command line will be strings, but default179-values and Python arguments may already be the correct type. The custom180-type should check at the top if the value is already valid and pass it181-through to support those cases.modified:CHANGES.rst+10 added-3 removed
3 unmodified lines4 --------------5 6 Unreleased7 8+- Don't discard pager arguments by correctly using subprocess.Popen. :issue:`3039` :pr:`3055`9+10+11+12+Version 8.3.013+--------------14+15+Released 2025-09-1716+17 - **Improved flag option handling**: Reworked the relationship between ``flag_value``18 and ``default`` parameters for better consistency:19 20 * The ``default`` parameter value is now preserved as-is and passed directly6 unmodified lines27 - Allow ``default`` to be set on ``Argument`` for ``nargs = -1``. :issue:`2164`28 :pr:`3030`29 - Show correct auto complete value for ``nargs`` option in combination with flag30 option :issue:`2813`22-- Show correct auto complete value for nargs option in combination with flag option :issue:`2813`31 - Fix handling of quoted and escaped parameters in Fish autocompletion. :issue:`2995` :pr:`3013`32 - Lazily import ``shutil``. :pr:`3023`33 - Properly forward exception information to resources registered with34 ``click.core.Context.with_resource()``. :issue:`2447` :pr:`3058`27-- Fix regression related to EOF handling in CliRunner. :issue:`2939`:pr:`2940`28-- Don't discard pager arguments. :issue:`3039` :pr:`3055`35+- Fix regression related to EOF handling in CliRunner. :issue:`2939` :pr:`2940`36 37 Version 8.2.238 -------------39 1262 unmodified linesmodified:pyproject.toml+2 added-2 removed
1 [project]2 name = "click"3-version = "8.2.2"3+version = "8.3.dev"4 description = "Composable command line interface toolkit"5 readme = "README.md"6 license = "BSD-3-Clause"7 license-files = ["LICENSE.txt"]49 unmodified lines57 "pytest",58 ]59 60 [build-system]61-requires = ["flit_core<4"]61+requires = ["flit_core>=3.11,<4"]62 build-backend = "flit_core.buildapi"63 64 [tool.flit.module]65 name = "click"143 unmodified linesmodified:uv.lock+1 added-1 removed
137 unmodified lines138 ]139 140 [[package]]141 name = "click"142-version = "8.2.2"142+version = "8.3.dev0"143 source = { editable = "." }144 dependencies = [145 { name = "colorama", marker = "sys_platform == 'win32'" },146 ]1076 unmodified lines