add an ExitStack to the context
Before adoption: this commit came in with the history the project adopted, so no landing records it.
This makes it possible to open a resource, make it available to callbacks and subcommands, then ensure the resource is cleaned up when the group ends and the context goes out of scope.
authored by Matthias Urlichs · committed by David Lord · parent d75ea33 · Browse files · 4 files·+143 added−12 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
4 files+143 added−12 removed
- tests:+18 added−0 removed
- other:+125 added−12 removed
Provenance
- Commit
8934907- Tree
b1e1816- Author
Matthias Urlichs <matthias@urlichs.de>- Committer
David Lord <davidism@gmail.com>- Parent
d75ea33
4 files changed+143 added−12 removed
modified:docs/advanced.rst+74 added
404 unmodified lines405 invoke(cli, prog_name='cli', args=[], env={"PORT": "8080"})406 println()407 invoke(cli, prog_name='cli', args=[])408 println()409+410+411+Managing Resources412+------------------413+414+It can be useful to open a resource in a group, to be made available to415+subcommands. Many types of resources need to be closed or otherwise416+cleaned up after use. The standard way to do this in Python is by using417+a context manager with the ``with`` statement.418+419+For example, the ``Repo`` class from :doc:`complex` might actually be420+defined as a context manager:421+422+.. code-block:: python423+424+ class Repo:425+ def __init__(self, home=None):426+ self.home = os.path.abspath(home or ".")427+ self.db = None428+429+ def __enter__(self):430+ path = os.path.join(self.home, "repo.db")431+ self.db = open_database(path)432+433+ def __exit__(self, exc_type, exc_value, tb):434+ self.db.close()435+436+Ordinarily, it would be used with the ``with`` statement:437+438+.. code-block:: python439+440+ with Repo() as repo:441+ repo.db.query(...)442+443+However, a ``with`` block in a group would exit and close the database444+before it could be used by a subcommand.445+446+Instead, use the context's :meth:`~click.Context.with_resource` method447+to enter the context manager and return the resource. When the group and448+any subcommands finish, the context's resources are cleaned up.449+450+.. code-block:: python451+452+ @click.group()453+ @click.option("--repo-home", default=".repo")454+ @click.pass_context455+ def cli(ctx, repo_home):456+ ctx.obj = ctx.with_resource(Repo(repo_home))457+458+ @cli.command()459+ @click.pass_obj460+ def log(obj):461+ # obj is the repo opened in the cli group462+ for entry in obj.db.query(...):463+ click.echo(entry)464+465+If the resource isn't a context manager, usually it can be wrapped in466+one using something from :mod:`contextlib`. If that's not possible, use467+the context's :meth:`~click.Context.call_on_close` method to register a468+cleanup function.469+470+.. code-block:: python471+472+ @click.group()473+ @click.option("--name", default="repo.db")474+ @click.pass_context475+ def cli(ctx, repo_home):476+ ctx.obj = db = open_db(repo_home)477+478+ @ctx.call_on_close479+ def close_db():480+ db.record_use()481+ db.save()482+ db.close()modified:src/click/core.py+46 added-12 removed
1 unmodified line2 import inspect3 import os4 import sys5 from contextlib import contextmanager6+from contextlib import ExitStack7 from functools import update_wrapper8 from itertools import repeat9 10 from ._unicodefun import _verify_python_env390 unmodified lines401 402 self._close_callbacks = []403 self._depth = 0404 self._source_by_paramname = {}405+ self._exit_stack = ExitStack()406 407 def __enter__(self):408 self._depth += 1409 push_context(self)84 unmodified lines494 return self.formatter_class(495 width=self.terminal_width, max_width=self.max_content_width496 )497 498+ def with_resource(self, context_manager):499+ """Register a resource as if it were used in a ``with``500+ statement. The resource will be cleaned up when the context is501+ popped.502+503+ Uses :meth:`contextlib.ExitStack.enter_context`. It calls the504+ resource's ``__enter__()`` method and returns the result. When505+ the context is popped, it closes the stack, which calls the506+ resource's ``__exit__()`` method.507+508+ To register a cleanup function for something that isn't a509+ context manager, use :meth:`call_on_close`. Or use something510+ from :mod:`contextlib` to turn it into a context manager first.511+512+ .. code-block:: python513+514+ @click.group()515+ @click.option("--name")516+ @click.pass_context517+ def cli(ctx):518+ ctx.obj = ctx.with_resource(connect_db(name))519+520+ :param context_manager: The context manager to enter.521+ :return: Whatever ``context_manager.__enter__()`` returns.522+523+ .. versionadded:: 8.0524+ """525+ return self._exit_stack.enter_context(context_manager)526+527 def call_on_close(self, f):497- """This decorator remembers a function as callback that should be498- executed when the context tears down. This is most useful to bind499- resource handling to the script execution. For instance, file objects500- opened by the :class:`File` type will register their close callbacks501- here.528+ """Register a function to be called when the context tears down.529 530+ This can be used to close resources opened during the script531+ execution. Resources that support Python's context manager532+ protocol which would be used in a ``with`` statement should be533+ registered with :meth:`with_resource` instead.534+503- :param f: the function to execute on teardown.535+ :param f: The function to execute on teardown.536 """505- self._close_callbacks.append(f)506- return f537+ return self._exit_stack.callback(f)538 539 def close(self):509- """Invokes all close callbacks."""510- for cb in self._close_callbacks:511- cb()512- self._close_callbacks = []540+ """Invoke all close callbacks registered with541+ :meth:`call_on_close`, and exit all context managers entered542+ with :meth:`with_resource`.543+ """544+ self._exit_stack.close()545+ # In case the context is reused, create a new exit stack.546+ self._exit_stack = ExitStack()547 548 @property549 def command_path(self):550 """The computed command path. This is used for the ``usage``1653 unmodified linesmodified:tests/test_context.py+18 added
1+from contextlib import contextmanager2+3 import pytest4 5 import click6 from click.core import ParameterSource206 unmodified lines213 assert result.output == "aha!\n"214 assert called == [True]215 216 217+def test_with_resource():218+ @contextmanager219+ def manager():220+ val = [1]221+ yield val222+ val[0] = 0223+224+ ctx = click.Context(click.Command("test"))225+226+ with ctx.scope():227+ rv = ctx.with_resource(manager())228+ assert rv[0] == 1229+230+ assert rv == [0]231+232+233 def test_make_pass_decorator_args(runner):234 """235 Test to check that make_pass_decorator doesn't consume arguments based on236 invocation order.109 unmodified linesmodified:CHANGES.rst+5 added
58 unmodified lines59 subgroups of the same type as the group itself.60 - Core objects use ``super()`` consistently for better support of61 subclassing.62 63+- Use ``Context.with_resource()`` to manage resources that would64+ normally be used in a ``with`` statement, allowing them to be used65+ across subcommands and callbacks, then cleaned up when the context66+ ends. :pr:`1191`67 68+69 Version 7.1.270 -------------71 72 Released 2020-04-27633 unmodified lines