Convert advanced.rst to MyST
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Veritia · committed by Veritia · parent 23780fa · Browse files · 2 files·+418 added−408 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
2 files+418 added−408 removed
- other:+418 added−408 removed
Provenance
- Commit
5aa9850- Tree
efa9c09- Author
Veritia <funkyvish88@gmail.com>- Committer
Veritia <funkyvish88@gmail.com>- Parent
23780fa
2 files changed+418 added−408 removed
added:docs/advanced.md+418 added
1+# Advanced Patterns2+3+```{eval-rst}4+.. currentmodule:: click5+```6+7+In addition to common functionality, Click offers some advanced features.8+9+```{contents}10+:depth: 111+:local: true12+```13+14+## Callbacks and Eager Options15+16+Sometimes, you want a parameter to completely change the execution flow.17+For instance, this is the case when you want to have a `--version`18+parameter that prints out the version and then exits the application.19+20+Note: an actual implementation of a `--version` parameter that is21+reusable is available in Click as {func}`click.version_option`. The code22+here is merely an example of how to implement such a flag.23+24+In such cases, you need two concepts: eager parameters and a callback. An25+eager parameter is a parameter handled before others, and a26+callback is what executes after the parameter is handled. The eagerness27+is necessary so that an earlier required parameter does not produce an28+error message. For instance, if `--version` was not eager and a29+parameter `--foo` was required and defined before, you would need to30+specify it for `--version` to work. For more information, see31+{ref}`callback-evaluation-order`.32+33+A callback is a function invoked with three parameters: the34+current {class}`Context`, the current {class}`Parameter`, and the value.35+The context provides some useful features such as quitting the36+application and gives access to other already processed parameters.37+38+Here's an example for a `--version` flag:39+40+```{eval-rst}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+56+# What it looks like:57+58+59+.. click:run::60+61+ invoke(hello)62+ invoke(hello, args=['--version'])63+```64+The `expose_value` parameter prevents the pretty pointless `version`65+parameter from being passed to the callback. If that was not specified, a66+boolean would be passed to the `hello` script. The `resilient_parsing`67+flag is applied to the context if Click wants to parse the command line68+without any destructive behavior that would change the execution flow. In69+this case, because we would exit the program, we instead do nothing.70+71+## Callbacks for Validation72+73+```{eval-rst}74+.. versionchanged:: 2.075+```76+77+If you want to apply custom validation logic, you can do this in the78+parameter callbacks. These callbacks can both modify values and79+raise errors if the validation does not work. The callback runs after80+type conversion. It is called for all sources, including prompts.81+82+In Click 1.0, you can only raise the {exc}`UsageError` but starting with83+Click 2.0, you can also raise the {exc}`BadParameter` error, which has the84+added advantage that it will automatically format the error message to85+also contain the parameter name.86+87+```{eval-rst}88+.. click:example::89+90+ def validate_rolls(ctx, param, value):91+ if isinstance(value, tuple):92+ return value93+94+ try:95+ rolls, _, dice = value.partition("d")96+ return int(dice), int(rolls)97+ except ValueError:98+ raise click.BadParameter("format must be 'NdM'")99+100+ @click.command()101+ @click.option(102+ "--rolls", type=click.UNPROCESSED, callback=validate_rolls,103+ default="1d6", prompt=True,104+ )105+ def roll(rolls):106+ sides, times = rolls107+ click.echo(f"Rolling a {sides}-sided dice {times} time(s)")108+109+.. click:run::110+111+ invoke(roll, args=["--rolls=42"])112+ println()113+ invoke(roll, args=["--rolls=2d12"])114+ println()115+ invoke(roll, input=["42", "2d12"])116+```117+118+## Parameter Modifications119+120+Parameters (options and arguments) are forwarded to the command callbacks,121+as you have seen. One common way to prevent a parameter from being passed122+to the callback is the `expose_value` argument to a parameter which hides123+the parameter entirely. The way this works is that the {class}`Context`124+object has a {attr}`~Context.params` attribute which is a dictionary of125+all parameters. Whatever is in that dictionary is being passed to the126+callbacks.127+128+This can be used to make up additional parameters. Generally, this pattern129+is not recommended, but in some cases it can be useful. At the very least,130+it's good to know that the system works this way.131+132+```{eval-rst}133+.. click:example::134+135+ import urllib136+137+ def open_url(ctx, param, value):138+ if value is not None:139+ ctx.params['fp'] = urllib.urlopen(value)140+ return value141+142+ @click.command()143+ @click.option('--url', callback=open_url)144+ def cli(url, fp=None):145+ if fp is not None:146+ click.echo(f"{url}: {fp.code}")147+148+In this case the callback returns the URL unchanged but also passes a149+second `fp` value to the callback. What's more recommended is to pass150+the information in a wrapper, however:151+152+.. click:example::153+154+ import urllib155+156+ class URL(object):157+158+ def __init__(self, url, fp):159+ self.url = url160+ self.fp = fp161+162+ def open_url(ctx, param, value):163+ if value is not None:164+ return URL(value, urllib.urlopen(value))165+166+ @click.command()167+ @click.option('--url', callback=open_url)168+ def cli(url):169+ if url is not None:170+ click.echo(f"{url.url}: {url.fp.code}")171+172+```173+174+## Token Normalization175+176+```{eval-rst}177+.. versionadded:: 2.0178+```179+180+Starting with Click 2.0, it's possible to provide a function used181+for normalizing tokens. Tokens are option names, choice values, or command182+values. This can be used to implement case-insensitive options, for183+instance.184+185+To use this feature, the context needs to be passed a function that186+performs the normalization of the token. Such as a function that converts the187+token to lowercase:188+189+```{eval-rst}190+.. click:example::191+192+ CONTEXT_SETTINGS = dict(token_normalize_func=lambda x: x.lower())193+194+ @click.command(context_settings=CONTEXT_SETTINGS)195+ @click.option('--name', default='Pete')196+ def cli(name):197+ click.echo(f"Name: {name}")198+199+# And how it works on the command line:200+201+.. click:run::202+203+ invoke(cli, prog_name='cli', args=['--NAME=Pete'])204+```205+206+## Invoking Other Commands207+208+Sometimes, it might be interesting to invoke one command from another209+command. This is a pattern generally discouraged with Click, but210+possible nonetheless. For this, you can use the {func}`Context.invoke`211+or {func}`Context.forward` methods.212+213+They work similarly, but the difference is that {func}`Context.invoke` merely214+invokes another command with the arguments you provide as a caller,215+whereas {func}`Context.forward` fills in the arguments from the current216+command. Both accept the command as the first argument, and everything else217+is passed onwards as you would expect.218+219+Example:220+221+```{eval-rst}222+.. click:example::223+224+ cli = click.Group()225+226+ @cli.command()227+ @click.option('--count', default=1)228+ def test(count):229+ click.echo(f'Count: {count}')230+231+ @cli.command()232+ @click.option('--count', default=1)233+ @click.pass_context234+ def dist(ctx, count):235+ ctx.forward(test)236+ ctx.invoke(test, count=42)237+238+And what it looks like:239+240+.. click:run::241+242+ invoke(cli, prog_name='cli', args=['dist'])243+```244+245+(forwarding-unknown-options)=246+247+## Forwarding Unknown Options248+249+In some situations, it is interesting to be able to accept all unknown250+options for further manual processing. Click can generally do that as of251+Click 4.0, but it has some limitations that lie in the nature of the252+problem. The support for this is provided through a parser flag called253+`ignore_unknown_options` which will instruct the parser to collect all254+unknown options and to put them to the leftover argument instead of255+triggering a parsing error.256+257+This can generally be activated in two different ways:258+259+1. It can be enabled on custom {class}`Command` subclasses by changing260+ the {attr}`~Command.ignore_unknown_options` attribute.261+2. It can be enabled by changing the attribute of the same name on the262+ context class ({attr}`Context.ignore_unknown_options`). This is best263+ changed through the `context_settings` dictionary on the command.264+265+For most situations, the easiest solution is the second. Once the behavior266+is changed, something needs to pick up those leftover options (which at267+this point are considered arguments). For this again, you have two268+options:269+270+1. You can use {func}`pass_context` to get the context passed. This will271+ only work if in addition to {attr}`~Context.ignore_unknown_options`272+ you also set {attr}`~Context.allow_extra_args` as otherwise the273+ command will abort with an error that there are leftover arguments.274+ If you go with this solution, the extra arguments will be collected in275+ {attr}`Context.args`.276+2. You can attach an {func}`argument` with `nargs` set to `-1` which277+ will eat up all leftover arguments. In this case it's recommended to278+ set the `type` to {data}`UNPROCESSED` to avoid any string processing279+ on those arguments as otherwise they are forced into Unicode strings280+ automatically which is often not what you want.281+282+In the end, the result looks something like this:283+284+```{eval-rst}285+.. click:example::286+287+ import sys288+ from subprocess import call289+290+ @click.command(context_settings=dict(291+ ignore_unknown_options=True,292+ ))293+ @click.option('-v', '--verbose', is_flag=True, help='Enables verbose mode')294+ @click.argument('timeit_args', nargs=-1, type=click.UNPROCESSED)295+ def cli(verbose, timeit_args):296+ """A fake wrapper around Python's timeit."""297+ cmdline = ['echo', 'python', '-mtimeit'] + list(timeit_args)298+ if verbose:299+ click.echo(f"Invoking: {' '.join(cmdline)}")300+ call(cmdline)301+302+303+And the final output resembles the following:304+305+.. click:run::306+307+ invoke(cli, prog_name='cli', args=['--help'])308+ println()309+ invoke(cli, prog_name='cli', args=['-n', '100', 'a = 1; b = 2; a * b'])310+ println()311+ invoke(cli, prog_name='cli', args=['-v', 'a = 1; b = 2; a * b'])312+```313+314+As you can see, Click handles the verbosity flag and everything else315+ends up in the `timeit_args` variable for further processing, which then316+for instance, allows invoking a subprocess. There are a few things that317+are important to know about how this ignoring of unhandled flag happens:318+319+- Unknown long options are generally ignored and not processed at all.320+ So for instance if `--foo=bar` or `--foo bar` are passed they321+ generally end up like that. Note that because the parser cannot know322+ if an option will accept an argument or not, the `bar` part might be323+ handled as an argument.324+- Unknown short options might be partially handled and reassembled if325+ necessary. For instance in the above example there is an option326+ called `-v` which enables verbose mode. If the command would be327+ ignored with `-va` then the `-v` part would be handled by Click328+ (as it is known) and `-a` would end up in the leftover parameters329+ for further processing.330+- Depending on what you plan on doing you might have some success by331+ disabling interspersed arguments332+ ({attr}`~Context.allow_interspersed_args`) which instructs the parser333+ to not allow arguments and options to be mixed. Depending on your334+ situation, this might improve your results.335+336+Generally, combining the handling of options and arguments from your own337+commands with those from another application is discouraged, and you338+should avoid it if possible. It's a much better idea to have339+everything below a subcommand be forwarded to another application than to340+handle some arguments yourself.341+342+## Managing Resources343+344+It can be useful to open a resource in a group, to be made available to345+subcommands. Many types of resources need to be closed or otherwise346+cleaned up after use. The standard way to do this in Python is by using347+a context manager with the `with` statement.348+349+For example, the `Repo` class from {doc}`complex` might actually be350+defined as a context manager:351+352+```python353+class Repo:354+ def __init__(self, home=None):355+ self.home = os.path.abspath(home or ".")356+ self.db = None357+358+ def __enter__(self):359+ path = os.path.join(self.home, "repo.db")360+ self.db = open_database(path)361+ return self362+363+ def __exit__(self, exc_type, exc_value, tb):364+ self.db.close()365+```366+367+Ordinarily, it would be used with the `with` statement:368+369+```python370+with Repo() as repo:371+ repo.db.query(...)372+```373+374+However, a `with` block in a group would exit and close the database375+before it could be used by a subcommand.376+377+Instead, use the context's {meth}`~click.Context.with_resource` method378+to enter the context manager and return the resource. When the group and379+any subcommands finish, the context's resources are cleaned up.380+381+```python382+@click.group()383+@click.option("--repo-home", default=".repo")384+@click.pass_context385+def cli(ctx, repo_home):386+ ctx.obj = ctx.with_resource(Repo(repo_home))387+388+@cli.command()389+@click.pass_obj390+def log(obj):391+ # obj is the repo opened in the cli group392+ for entry in obj.db.query(...):393+ click.echo(entry)394+```395+396+If the resource isn't a context manager, usually it can be wrapped in397+one using something from {mod}`contextlib`. If that's not possible, use398+the context's {meth}`~click.Context.call_on_close` method to register a399+cleanup function.400+401+```python402+@click.group()403+@click.option("--name", default="repo.db")404+@click.pass_context405+def cli(ctx, repo_home):406+ ctx.obj = db = open_db(repo_home)407+408+ @ctx.call_on_close409+ def close_db():410+ db.record_use()411+ db.save()412+ db.close()413+```414+415+```{versionchanged} 8.2416+`Context.call_on_close` and context managers registered via `Context.with_resource`417+will be closed when the CLI exits. These were previously not called on exit.418+```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.