Skip to content
Myr

refactor from rest to myst

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

authored by denuoweb · committed by denuoweb · parent 3df7be3 · Browse files · 1 file+180 added−188 removed
This commit

State

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

Diff stats

1 file+180 added−188 removed

  • other:+180 added−188 removed

1 file+180 added−188 removed

modified:docs/complex.md+180 added-188 removed
1.. _complex-guide:1(complex-guide)=23Complex Applications4====================3# Complex Applications46.. currentmodule:: click5```{currentmodule} click6```78Click is designed to assist with the creation of complex and simple CLI tools9alike. However, the power of its design is the ability to arbitrarily nest10systems together. For instance, if you have ever used Django, you will
4 unmodified lines
15In a theoretical world of two separate Click command line utilities, they16could solve this problem by nesting one inside the other. For instance, the17web framework could also load the commands for the message queue framework.1819.. contents::20 :depth: 121 :local:19```{contents}20---21depth: 122local: true23---24```2523Basic Concepts24--------------26## Basic Concepts2728To understand how this works, you need to understand two concepts: contexts29and the calling convention.3029Contexts30````````31### Contexts3232Whenever a Click command is executed, a :class:`Context` object is created33Whenever a Click command is executed, a {class}`Context` object is created34which holds state for this particular invocation. It remembers parsed35parameters, what command created it, which resources need to be cleaned up36at the end of the function, and so forth. It can also optionally hold an37application-defined object.
8 unmodified lines
4647Most of the time, you do not see the context object, but when writing more48complex applications it comes in handy. This brings us to the next point.4949Calling Convention50``````````````````50### Calling Convention5152When a Click command callback is executed, it's passed all the non-hidden53parameters as keyword arguments. Notably absent is the context. However,54a callback can opt into being passed to the context object by marking itself55with :func:`pass_context`.55with {func}`pass_context`.5657So how do you invoke a command callback if you don't know if it should58receive the context or not? The answer is that the context itself59provides a helper function (:meth:`Context.invoke`) which can do this for59provides a helper function ({meth}`Context.invoke`) which can do this for60you. It accepts the callback as first argument and then invokes the61function correctly.6263Building a Git Clone64--------------------63## Building a Git Clone6465In this example, we want to build a command line tool that resembles a66version control system. Systems like Git usually provide one67over-arching command that already accepts some parameters and68configuration, and then have extra subcommands that do other things.6971The Root Command72````````````````70### The Root Command7172At the top level, we need a group that can hold all our commands. In this75case, we use the basic :func:`click.group` which allows us to register73case, we use the basic {func}`click.group` which allows us to register74other Click commands below it.7576For this command, we also want to accept some parameters that configure the77state of our tool:7879```{eval-rst}80.. click:example::8182 import os83 import click
11 unmodified lines
95 envvar='REPO_DEBUG')96 @click.pass_context97 def cli(ctx, repo_home, debug):98 ctx.obj = Repo(repo_home, debug)99```100101101Let's understand what this does. We create a group command which can102have subcommands. When it is invoked, it will create an instance of a104``Repo`` class. This holds the state for our command line tool. In this103`Repo` class. This holds the state for our command line tool. In this104case, it just remembers some parameters, but at this point it could also105start loading configuration files and so on.106108This state object is then remembered by the context as :attr:`~Context.obj`.107This state object is then remembered by the context as {attr}`~Context.obj`.108This is a special attribute where commands are supposed to remember what109they need to pass on to their children.110111In order for this to work, we need to mark our function with113:func:`pass_context`, because otherwise, the context object would be112{func}`pass_context`, because otherwise, the context object would be113entirely hidden from us.114116The First Child Command117```````````````````````115### The First Child Command116117Let's add our first child command to it, the clone command:118121.. click:example::119```python120@cli.command()121@click.argument('src')122@click.argument('dest', required=False)123def clone(src, dest):124 pass125```126123 @cli.command()124 @click.argument('src')125 @click.argument('dest', required=False)126 def clone(src, dest):127 pass128127So now we have a clone command, but how do we get access to the repo? As130you can imagine, one way is to use the :func:`pass_context` function which128you can imagine, one way is to use the {func}`pass_context` function which129again will make our callback also get the context passed on which we130memorized the repo. However, there is a second version of this decorator133called :func:`pass_obj` which will just pass the stored object, (in our case131called {func}`pass_obj` which will just pass the stored object, (in our case132the repo):133136.. click:example::134```python135@cli.command()136@click.argument('src')137@click.argument('dest', required=False)138@click.pass_obj139def clone(repo, src, dest):140 pass141```142138 @cli.command()139 @click.argument('src')140 @click.argument('dest', required=False)141 @click.pass_obj142 def clone(repo, src, dest):143 pass143### Interleaved Commands144145Interleaved Commands146````````````````````147145While not relevant for the particular program we want to build, there is146also quite good support for interleaving systems. Imagine for instance that147there was a super cool plugin for our version control system that needed a148lot of configuration and wanted to store its own configuration as152:attr:`~Context.obj`. If we would then attach another command below that,149{attr}`~Context.obj`. If we would then attach another command below that,150we would all of a sudden get the plugin configuration instead of our repo151object.152153One obvious way to remedy this is to store a reference to the repo in the
4 unmodified lines
158linked nature of contexts. We know that the plugin context is linked to the159context that created our repo. Because of that, we can start a search for160the last level where the object stored by the context was a repo.161165Built-in support for this is provided by the :func:`make_pass_decorator`162Built-in support for this is provided by the {func}`make_pass_decorator`163factory, which will create decorators for us that find objects (it167internally calls into :meth:`Context.find_object`). In our case, we168know that we want to find the closest ``Repo`` object, so let's make a164internally calls into {meth}`Context.find_object`). In our case, we165know that we want to find the closest `Repo` object, so let's make a166decorator for this:167171.. click:example::168```python169pass_repo = click.make_pass_decorator(Repo)170```171173 pass_repo = click.make_pass_decorator(Repo)174175If we now use ``pass_repo`` instead of ``pass_obj``, we will always get a172If we now use `pass_repo` instead of `pass_obj`, we will always get a173repo instead of something else:174178.. click:example::175```python176@cli.command()177@click.argument('src')178@click.argument('dest', required=False)179@pass_repo180def clone(repo, src, dest):181 pass182```183180 @cli.command()181 @click.argument('src')182 @click.argument('dest', required=False)183 @pass_repo184 def clone(repo, src, dest):185 pass184### Ensuring Object Creation185187Ensuring Object Creation188````````````````````````189186The above example only works if there was an outer command that created a191``Repo`` object and stored it in the context. For some more advanced use187`Repo` object and stored it in the context. For some more advanced use188cases, this might become a problem. The default behavior of193:func:`make_pass_decorator` is to call :meth:`Context.find_object`189{func}`make_pass_decorator` is to call {meth}`Context.find_object`190which will find the object. If it can't find the object,195:meth:`make_pass_decorator` will raise an error.196The alternative behavior is to use :meth:`Context.ensure_object`191{meth}`make_pass_decorator` will raise an error.192The alternative behavior is to use {meth}`Context.ensure_object`193which will find the object, and if it cannot find it, will create one and194store it in the innermost context. This behavior can also be enabled for199:func:`make_pass_decorator` by passing ``ensure=True``:195{func}`make_pass_decorator` by passing `ensure=True`:196201.. click:example::197```python198pass_repo = click.make_pass_decorator(Repo, ensure=True)199```200203 pass_repo = click.make_pass_decorator(Repo, ensure=True)204201In this case, the innermost context gets an object created if it is202missing. This might replace objects being placed there earlier. In this203case, the command stays executable, even if the outer command does not run.204For this to work, the object type needs to have a constructor that accepts205no arguments.206207As such it runs standalone:208213.. click:example::214209```python210 @click.command()211 @pass_repo212 def cp(repo):213 click.echo(isinstance(repo, Repo))219214```215As you can see:216222.. click:run::217```console218$ cp219True220```221224 invoke(cp, [])222## Lazily Loading Subcommands223226Lazily Loading Subcommands227--------------------------228224Large CLIs and CLIs with slow imports may benefit from deferring the loading of225subcommands. The interfaces which support this mode of use are231:meth:`Group.list_commands` and :meth:`Group.get_command`. A custom232:class:`Group` subclass can implement a lazy loader by storing extra data such233that :meth:`Group.get_command` is responsible for running imports.226{meth}`Group.list_commands` and {meth}`Group.get_command`. A custom227{class}`Group` subclass can implement a lazy loader by storing extra data such228that {meth}`Group.get_command` is responsible for running imports.229235Since the primary case for this is a :class:`Group` which loads its subcommands lazily,230Since the primary case for this is a {class}`Group` which loads its subcommands lazily,231the following example shows a lazy-group implementation.232238.. warning::233```{warning}234Lazy loading of python code can result in hard to track down bugs, circular imports235in order-dependent codebases, and other surprising behaviors. It is recommended that236this technique only be used in concert with testing which will at least run the237`--help` on each subcommand. That will guarantee that each subcommand can be loaded238successfully.239```240240 Lazy loading of python code can result in hard to track down bugs, circular imports241 in order-dependent codebases, and other surprising behaviors. It is recommended that242 this technique only be used in concert with testing which will at least run the243 ``--help`` on each subcommand. That will guarantee that each subcommand can be loaded244 successfully.241### Defining the Lazy Group242246Defining the Lazy Group247```````````````````````248249The following :class:`Group` subclass adds an attribute, ``lazy_subcommands``, which243The following {class}`Group` subclass adds an attribute, `lazy_subcommands`, which244stores a mapping from subcommand names to the information for importing them.245252.. code-block:: python246247```python254 # in lazy_group.py255 import importlib256 import click248# in lazy_group.py249import importlib250import click251258 class LazyGroup(click.Group):259 def __init__(self, *args, lazy_subcommands=None, **kwargs):260 super().__init__(*args, **kwargs)261 # lazy_subcommands is a map of the form:262 #263 # {command-name} -> {module-name}.{command-object-name}264 #265 self.lazy_subcommands = lazy_subcommands or {}252class LazyGroup(click.Group):253 def __init__(self, *args, lazy_subcommands=None, **kwargs):254 super().__init__(*args, **kwargs)255 # lazy_subcommands is a map of the form:256 #257 # {command-name} -> {module-name}.{command-object-name}258 #259 self.lazy_subcommands = lazy_subcommands or {}260267 def list_commands(self, ctx):268 base = super().list_commands(ctx)269 lazy = sorted(self.lazy_subcommands.keys())270 return base + lazy261 def list_commands(self, ctx):262 base = super().list_commands(ctx)263 lazy = sorted(self.lazy_subcommands.keys())264 return base + lazy265272 def get_command(self, ctx, cmd_name):273 if cmd_name in self.lazy_subcommands:274 return self._lazy_load(cmd_name)275 return super().get_command(ctx, cmd_name)266 def get_command(self, ctx, cmd_name):267 if cmd_name in self.lazy_subcommands:268 return self._lazy_load(cmd_name)269 return super().get_command(ctx, cmd_name)270277 def _lazy_load(self, cmd_name):278 # lazily loading a command, first get the module name and attribute name279 import_path = self.lazy_subcommands[cmd_name]280 modname, cmd_object_name = import_path.rsplit(".", 1)281 # do the import282 mod = importlib.import_module(modname)283 # get the Command object from that module284 cmd_object = getattr(mod, cmd_object_name)285 # check the result to make debugging easier286 if not isinstance(cmd_object, click.Command):287 raise ValueError(288 f"Lazy loading of {import_path} failed by returning "289 "a non-command object"290 )291 return cmd_object271 def _lazy_load(self, cmd_name):272 # lazily loading a command, first get the module name and attribute name273 import_path = self.lazy_subcommands[cmd_name]274 modname, cmd_object_name = import_path.rsplit(".", 1)275 # do the import276 mod = importlib.import_module(modname)277 # get the Command object from that module278 cmd_object = getattr(mod, cmd_object_name)279 # check the result to make debugging easier280 if not isinstance(cmd_object, click.Command):281 raise ValueError(282 f"Lazy loading of {import_path} failed by returning "283 "a non-command object"284 )285 return cmd_object286```287293Using LazyGroup To Define a CLI294```````````````````````````````288### Using LazyGroup To Define a CLI289296With ``LazyGroup`` defined, it's now possible to write a group which lazily loads its290With `LazyGroup` defined, it's now possible to write a group which lazily loads its291subcommands like so:292299.. code-block:: python293```python294# in main.py295import click296from lazy_group import LazyGroup297301 # in main.py302 import click303 from lazy_group import LazyGroup298@click.group(299 cls=LazyGroup,300 lazy_subcommands={"foo": "foo.cli", "bar": "bar.cli"},301 help="main CLI command for lazy example",302)303def cli():304 pass305```306305 @click.group(306 cls=LazyGroup,307 lazy_subcommands={"foo": "foo.cli", "bar": "bar.cli"},308 help="main CLI command for lazy example",309 )310 def cli():311 pass307```python308# in foo.py309import click310313.. code-block:: python311@click.group(help="foo command for lazy example")312def cli():313 pass314```315```python316# in bar.py317import click318from lazy_group import LazyGroup319315 # in foo.py316 import click320@click.group(321 cls=LazyGroup,322 lazy_subcommands={"baz": "baz.cli"},323 help="bar command for lazy example",324)325def cli():326 pass327```328318 @click.group(help="foo command for lazy example")319 def cli():320 pass329```python330# in baz.py331import click332322.. code-block:: python333@click.group(help="baz command for lazy example")334def cli():335 pass336```337324 # in bar.py325 import click326 from lazy_group import LazyGroup338### What triggers Lazy Loading?339328 @click.group(329 cls=LazyGroup,330 lazy_subcommands={"baz": "baz.cli"},331 help="bar command for lazy example",332 )333 def cli():334 pass335336.. code-block:: python337338 # in baz.py339 import click340341 @click.group(help="baz command for lazy example")342 def cli():343 pass344345346What triggers Lazy Loading?347```````````````````````````348340There are several events which may trigger lazy loading by running the350:meth:`Group.get_command` function.341{meth}`Group.get_command` function.342Some are intuititve, and some are less so.343353All cases are described with respect to the above example, assuming the main program354name is ``cli``.344All cases are described with respect to the above example, assuming the main progra345name is `cli`.3463561. Command resolution. If a user runs ``cli bar baz``, this must first resolve ``bar``,357 and then resolve ``baz``. Each subcommand resolution step does a lazy load.3471. Command resolution. If a user runs `cli bar baz`, this must first resolve `bar`,348 and then resolve `baz`. Each subcommand resolution step does a lazy load.3492. Helptext rendering. In order to get the short help description of subcommands,359 ``cli --help`` will load ``foo`` and ``bar``. Note that it will still not load360 ``baz``.3613. Shell completion. In order to get the subcommands of a lazy command, ``cli <TAB>``362 will need to resolve the subcommands of ``cli``. This process will trigger the lazy350 `cli --help` will load `foo` and `bar`. Note that it will still not load351 `baz`.3523. Shell completion. In order to get the subcommands of a lazy command, `cli <TAB>`353 will need to resolve the subcommands of `cli`. This process will trigger the lazy354 loads.355365Further Deferring Imports366`````````````````````````356### Further Deferring Imports357358It is possible to make the process even lazier, but it is generally more difficult the359more you want to defer work.360371For example, subcommands could be represented as a custom :class:`Command` subclass361For example, subcommands could be represented as a custom {class}`Command` subclass362which defers importing the command until it is invoked, but which provides373:meth:`Command.get_short_help_str` in order to support completions and helptext.363{meth}`Command.get_short_help_str` in order to support completions and helptext.364More simply, commands can be constructed whose callback functions defer any actual work365until after an import.366377This command definition provides ``foo``, but any of the work associated with importing367This command definition provides `foo`, but any of the work associated with importing368the "real" callback function is deferred until invocation time:369370```{eval-rst}371.. click:example::372373 @click.command()374 @click.option("-n", type=int)
1 unmodified line
376 def foo(n, w):377 from mylibrary import foo_concrete378379 foo_concrete(n, w)380```381382Because Click builds helptext and usage info from options, arguments, and command383attributes, it has no awareness that the underlying function is in any way handling a384deferred import. Therefore, all Click-provided utilities and functionality will work
1 unmodified line