Skip to content
Myr

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

4 files+143 added−12 removed

modified:docs/advanced.rst+74 added
404 unmodified lines
405 invoke(cli, prog_name='cli', args=[], env={"PORT": "8080"})406 println()407 invoke(cli, prog_name='cli', args=[])408 println()409410411Managing Resources412------------------413414It can be useful to open a resource in a group, to be made available to415subcommands. Many types of resources need to be closed or otherwise416cleaned up after use. The standard way to do this in Python is by using417a context manager with the ``with`` statement.418419For example, the ``Repo`` class from :doc:`complex` might actually be420defined as a context manager:421422.. code-block:: python423424 class Repo:425 def __init__(self, home=None):426 self.home = os.path.abspath(home or ".")427 self.db = None428429 def __enter__(self):430 path = os.path.join(self.home, "repo.db")431 self.db = open_database(path)432433 def __exit__(self, exc_type, exc_value, tb):434 self.db.close()435436Ordinarily, it would be used with the ``with`` statement:437438.. code-block:: python439440 with Repo() as repo:441 repo.db.query(...)442443However, a ``with`` block in a group would exit and close the database444before it could be used by a subcommand.445446Instead, use the context's :meth:`~click.Context.with_resource` method447to enter the context manager and return the resource. When the group and448any subcommands finish, the context's resources are cleaned up.449450.. code-block:: python451452 @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))457458 @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)464465If the resource isn't a context manager, usually it can be wrapped in466one using something from :mod:`contextlib`. If that's not possible, use467the context's :meth:`~click.Context.call_on_close` method to register a468cleanup function.469470.. code-block:: python471472 @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)477478 @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 line
2import inspect3import os4import sys5from contextlib import contextmanager6from contextlib import ExitStack7from functools import update_wrapper8from itertools import repeat910from ._unicodefun import _verify_python_env
390 unmodified lines
401402 self._close_callbacks = []403 self._depth = 0404 self._source_by_paramname = {}405 self._exit_stack = ExitStack()406407 def __enter__(self):408 self._depth += 1409 push_context(self)
84 unmodified lines
494 return self.formatter_class(495 width=self.terminal_width, max_width=self.max_content_width496 )497498 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.502503 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.507508 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.511512 .. code-block:: python513514 @click.group()515 @click.option("--name")516 @click.pass_context517 def cli(ctx):518 ctx.obj = ctx.with_resource(connect_db(name))519520 :param context_manager: The context manager to enter.521 :return: Whatever ``context_manager.__enter__()`` returns.522523 .. versionadded:: 8.0524 """525 return self._exit_stack.enter_context(context_manager)526527 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.529530 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.534503 :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)538539 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()547548 @property549 def command_path(self):550 """The computed command path. This is used for the ``usage``
1653 unmodified lines
modified:tests/test_context.py+18 added
1from contextlib import contextmanager23import pytest45import click6from click.core import ParameterSource
206 unmodified lines
213 assert result.output == "aha!\n"214 assert called == [True]215216217def test_with_resource():218 @contextmanager219 def manager():220 val = [1]221 yield val222 val[0] = 0223224 ctx = click.Context(click.Command("test"))225226 with ctx.scope():227 rv = ctx.with_resource(manager())228 assert rv[0] == 1229230 assert rv == [0]231232233def 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 lines
modified:CHANGES.rst+5 added
58 unmodified lines
59 subgroups of the same type as the group itself.60 - Core objects use ``super()`` consistently for better support of61 subclassing.6263- 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`676869Version 7.1.270-------------7172Released 2020-04-27
633 unmodified lines