complex.md
This file
Path
docs/complex.md
386 lines · 12.6 KiB · Markdown
Last changed by
Stable (#3851)Rowlando13before adoption6aabf09
History of this fileTake it
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387(complex-guide)=
# Complex Applications
```{currentmodule} click```
Click is designed to assist with the creation of complex and simple CLI toolsalike. However, the power of its design is the ability to arbitrarily nestsystems together. For instance, if you have ever used Django, you willhave realized that it provides a command line utility, but so does Celery.When using Celery with Django, there are two tools that need to interact witheach other and be cross-configured.
In a theoretical world of two separate Click command line utilities, theycould solve this problem by nesting one inside the other. For instance, theweb framework could also load the commands for the message queue framework.
```{contents}---depth: 1local: true---```
## Basic Concepts
To understand how this works, you need to understand two concepts: contextsand the calling convention.
### Contexts
Whenever a Click command is executed, a {class}`Context` object is createdwhich holds state for this particular invocation. It remembers parsedparameters, what command created it, which resources need to be cleaned upat the end of the function, and so forth. It can also optionally hold anapplication-defined object.
Context objects build a linked list until they hit the top one. Each contextis linked to a parent context. This allows a command to work belowanother command and store its own information there without having to beafraid of altering up the state of the parent command.
Because the parent data is available, however, it is possible to navigate toit if needed.
Most of the time, you do not see the context object, but when writing morecomplex applications it comes in handy. This brings us to the next point.
### Calling Convention
When a Click command callback is executed, it's passed all the non-hiddenparameters as keyword arguments. Notably absent is the context. However,a callback can opt into being passed to the context object by marking itselfwith {func}`pass_context`.
So how do you invoke a command callback if you don't know if it shouldreceive the context or not? The answer is that the context itselfprovides a helper function ({meth}`Context.invoke`) which can do this foryou. It accepts the callback as first argument and then invokes thefunction correctly.
## Building a Git Clone
In this example, we want to build a command line tool that resembles aversion control system. Systems like Git usually provide oneover-arching command that already accepts some parameters andconfiguration, and then have extra subcommands that do other things.
### The Root Command
At the top level, we need a group that can hold all our commands. In thiscase, we use the basic {func}`click.group` which allows us to registerother Click commands below it.
For this command, we also want to accept some parameters that configure thestate of our tool:
```{eval-rst}.. click:example::
import os import click
class Repo(object): def __init__(self, home=None, debug=False): self.home = os.path.abspath(home or '.') self.debug = debug
@click.group() @click.option('--repo-home', envvar='REPO_HOME', default='.repo') @click.option('--debug/--no-debug', default=False, envvar='REPO_DEBUG') @click.pass_context def cli(ctx, repo_home, debug): ctx.obj = Repo(repo_home, debug)```
Let's understand what this does. We create a group command which canhave subcommands. When it is invoked, it will create an instance of a`Repo` class. This holds the state for our command line tool. In thiscase, it just remembers some parameters, but at this point it could alsostart loading configuration files and so on.
This state object is then remembered by the context as {attr}`~Context.obj`.This is a special attribute where commands are supposed to remember whatthey need to pass on to their children.
In order for this to work, we need to mark our function with{func}`pass_context`, because otherwise, the context object would beentirely hidden from us.
### The First Child Command
Let's add our first child command to it, the clone command:
```python@cli.command()@click.argument('src')@click.argument('dest', required=False)def clone(src, dest): pass```
So now we have a clone command, but how do we get access to the repo? Asyou can imagine, one way is to use the {func}`pass_context` function whichagain will make our callback also get the context passed on which wememorized the repo. However, there is a second version of this decoratorcalled {func}`pass_obj` which will just pass the stored object, (in our casethe repo):
```python@cli.command()@click.argument('src')@click.argument('dest', required=False)@click.pass_objdef clone(repo, src, dest): pass```
### Interleaved Commands
While not relevant for the particular program we want to build, there isalso quite good support for interleaving systems. Imagine for instance thatthere was a super cool plugin for our version control system that needed alot of configuration and wanted to store its own configuration as{attr}`~Context.obj`. If we would then attach another command below that,we would all of a sudden get the plugin configuration instead of our repoobject.
One obvious way to remedy this is to store a reference to the repo in theplugin, but then a command needs to be aware that it's attached below such aplugin.
There is a much better system that can be built by taking advantage of thelinked nature of contexts. We know that the plugin context is linked to thecontext that created our repo. Because of that, we can start a search forthe last level where the object stored by the context was a repo.
Built-in support for this is provided by the {func}`make_pass_decorator`factory, which will create decorators for us that find objects (itinternally calls into {meth}`Context.find_object`). In our case, weknow that we want to find the closest `Repo` object, so let's make adecorator for this:
```pythonpass_repo = click.make_pass_decorator(Repo)```
If we now use `pass_repo` instead of `pass_obj`, we will always get arepo instead of something else:
```python@cli.command()@click.argument('src')@click.argument('dest', required=False)@pass_repodef clone(repo, src, dest): pass```
### Ensuring Object Creation
The above example only works if there was an outer command that created a`Repo` object and stored it in the context. For some more advanced usecases, this might become a problem. The default behavior of{func}`make_pass_decorator` is to call {meth}`Context.find_object`which will find the object. If it can't find the object,{meth}`make_pass_decorator` will raise an error.The alternative behavior is to use {meth}`Context.ensure_object`which will find the object, and if it cannot find it, will create one andstore it in the innermost context. This behavior can also be enabled for{func}`make_pass_decorator` by passing `ensure=True`:
```pythonpass_repo = click.make_pass_decorator(Repo, ensure=True)```
In this case, the innermost context gets an object created if it ismissing. This might replace objects being placed there earlier. In thiscase, the command stays executable, even if the outer command does not run.For this to work, the object type needs to have a constructor that acceptsno arguments.
As such it runs standalone:
```python@click.command()@pass_repodef cp(repo): click.echo(isinstance(repo, Repo))```As you can see:
```console$ cpTrue```
## Lazily Loading Subcommands
Large CLIs and CLIs with slow imports may benefit from deferring the loading ofsubcommands. The interfaces which support this mode of use are{meth}`Group.list_commands` and {meth}`Group.get_command`. A custom{class}`Group` subclass can implement a lazy loader by storing extra data suchthat {meth}`Group.get_command` is responsible for running imports.
Since the primary case for this is a {class}`Group` which loads its subcommands lazily,the following example shows a lazy-group implementation.
```{warning}Lazy loading of python code can result in hard to track down bugs, circular importsin order-dependent codebases, and other surprising behaviors. It is recommended thatthis technique only be used in concert with testing which will at least run the`--help` on each subcommand. That will guarantee that each subcommand can be loadedsuccessfully.```
### Defining the Lazy Group
The following {class}`Group` subclass adds an attribute, `lazy_subcommands`, whichstores a mapping from subcommand names to the information for importing them.
```python# in lazy_group.pyimport importlibimport click
class LazyGroup(click.Group): def __init__(self, *args, lazy_subcommands=None, **kwargs): super().__init__(*args, **kwargs) # lazy_subcommands is a map of the form: # # {command-name} -> {module-name}.{command-object-name} # self.lazy_subcommands = lazy_subcommands or {}
def list_commands(self, ctx): base = super().list_commands(ctx) lazy = sorted(self.lazy_subcommands.keys()) return base + lazy
def get_command(self, ctx, cmd_name): if cmd_name in self.lazy_subcommands: return self._lazy_load(cmd_name) return super().get_command(ctx, cmd_name)
def _lazy_load(self, cmd_name): # lazily loading a command, first get the module name and attribute name import_path = self.lazy_subcommands[cmd_name] modname, cmd_object_name = import_path.rsplit(".", 1) # do the import mod = importlib.import_module(modname) # get the Command object from that module cmd_object = getattr(mod, cmd_object_name) # check the result to make debugging easier if not isinstance(cmd_object, click.Command): raise ValueError( f"Lazy loading of {import_path} failed by returning " "a non-command object" ) return cmd_object```
### Using LazyGroup To Define a CLI
With `LazyGroup` defined, it's now possible to write a group which lazily loads itssubcommands like so:
```python# in main.pyimport clickfrom lazy_group import LazyGroup
@click.group( cls=LazyGroup, lazy_subcommands={"foo": "foo.cli", "bar": "bar.cli"}, help="main CLI command for lazy example",)def cli(): pass```
```python# in foo.pyimport click
@click.group(help="foo command for lazy example")def cli(): pass```
```python# in bar.pyimport clickfrom lazy_group import LazyGroup
@click.group( cls=LazyGroup, lazy_subcommands={"baz": "baz.cli"}, help="bar command for lazy example",)def cli(): pass```
```python# in baz.pyimport click
@click.group(help="baz command for lazy example")def cli(): pass```
### What triggers Lazy Loading?
There are several events which may trigger lazy loading by running the{meth}`Group.get_command` function.Some are intuititve, and some are less so.
All cases are described with respect to the above example, assuming the main programname is `cli`.
1. Command resolution. If a user runs `cli bar baz`, this must first resolve `bar`, and then resolve `baz`. Each subcommand resolution step does a lazy load.2. Helptext rendering. In order to get the short help description of subcommands, `cli --help` will load `foo` and `bar`. Note that it will still not load `baz`.3. Shell completion. In order to get the subcommands of a lazy command, completing `cli` with {kbd}`Tab` will need to resolve the subcommands of `cli`. This process will trigger the lazy loads.
### Further Deferring Imports
It is possible to make the process even lazier, but it is generally more difficult themore you want to defer work.
For example, subcommands could be represented as a custom {class}`Command` subclasswhich defers importing the command until it is invoked, but which provides{meth}`Command.get_short_help_str` in order to support completions and helptext.More simply, commands can be constructed whose callback functions defer any actual workuntil after an import.
This command definition provides `foo`, but any of the work associated with importingthe "real" callback function is deferred until invocation time:
```{eval-rst}.. click:example::
@click.command() @click.option("-n", type=int) @click.option("-w", type=str) def foo(n, w): from mylibrary import foo_concrete
foo_concrete(n, w)```
Because Click builds helptext and usage info from options, arguments, and commandattributes, it has no awareness that the underlying function is in any way handling adeferred import. Therefore, all Click-provided utilities and functionality will workas normal on such a command.