| 1 |
(complex-guide)= |
| 2 |
|
| 3 |
# Complex Applications |
| 4 |
|
| 5 |
```{currentmodule} click |
| 6 |
``` |
| 7 |
|
| 8 |
Click is designed to assist with the creation of complex and simple CLI tools |
| 9 |
alike. However, the power of its design is the ability to arbitrarily nest |
| 10 |
systems together. For instance, if you have ever used Django, you will |
| 11 |
have realized that it provides a command line utility, but so does Celery. |
| 12 |
When using Celery with Django, there are two tools that need to interact with |
| 13 |
each other and be cross-configured. |
| 14 |
|
| 15 |
In a theoretical world of two separate Click command line utilities, they |
| 16 |
could solve this problem by nesting one inside the other. For instance, the |
| 17 |
web framework could also load the commands for the message queue framework. |
| 18 |
|
| 19 |
```{contents} |
| 20 |
--- |
| 21 |
depth: 1 |
| 22 |
local: true |
| 23 |
--- |
| 24 |
``` |
| 25 |
|
| 26 |
## Basic Concepts |
| 27 |
|
| 28 |
To understand how this works, you need to understand two concepts: contexts |
| 29 |
and the calling convention. |
| 30 |
|
| 31 |
### Contexts |
| 32 |
|
| 33 |
Whenever a Click command is executed, a {class}`Context` object is created |
| 34 |
which holds state for this particular invocation. It remembers parsed |
| 35 |
parameters, what command created it, which resources need to be cleaned up |
| 36 |
at the end of the function, and so forth. It can also optionally hold an |
| 37 |
application-defined object. |
| 38 |
|
| 39 |
Context objects build a linked list until they hit the top one. Each context |
| 40 |
is linked to a parent context. This allows a command to work below |
| 41 |
another command and store its own information there without having to be |
| 42 |
afraid of altering up the state of the parent command. |
| 43 |
|
| 44 |
Because the parent data is available, however, it is possible to navigate to |
| 45 |
it if needed. |
| 46 |
|
| 47 |
Most of the time, you do not see the context object, but when writing more |
| 48 |
complex applications it comes in handy. This brings us to the next point. |
| 49 |
|
| 50 |
### Calling Convention |
| 51 |
|
| 52 |
When a Click command callback is executed, it's passed all the non-hidden |
| 53 |
parameters as keyword arguments. Notably absent is the context. However, |
| 54 |
a callback can opt into being passed to the context object by marking itself |
| 55 |
with {func}`pass_context`. |
| 56 |
|
| 57 |
So how do you invoke a command callback if you don't know if it should |
| 58 |
receive the context or not? The answer is that the context itself |
| 59 |
provides a helper function ({meth}`Context.invoke`) which can do this for |
| 60 |
you. It accepts the callback as first argument and then invokes the |
| 61 |
function correctly. |
| 62 |
|
| 63 |
## Building a Git Clone |
| 64 |
|
| 65 |
In this example, we want to build a command line tool that resembles a |
| 66 |
version control system. Systems like Git usually provide one |
| 67 |
over-arching command that already accepts some parameters and |
| 68 |
configuration, and then have extra subcommands that do other things. |
| 69 |
|
| 70 |
### The Root Command |
| 71 |
|
| 72 |
At the top level, we need a group that can hold all our commands. In this |
| 73 |
case, we use the basic {func}`click.group` which allows us to register |
| 74 |
other Click commands below it. |
| 75 |
|
| 76 |
For this command, we also want to accept some parameters that configure the |
| 77 |
state of our tool: |
| 78 |
|
| 79 |
```{eval-rst} |
| 80 |
.. click:example:: |
| 81 |
|
| 82 |
import os |
| 83 |
import click |
| 84 |
|
| 85 |
|
| 86 |
class Repo(object): |
| 87 |
def __init__(self, home=None, debug=False): |
| 88 |
self.home = os.path.abspath(home or '.') |
| 89 |
self.debug = debug |
| 90 |
|
| 91 |
|
| 92 |
@click.group() |
| 93 |
@click.option('--repo-home', envvar='REPO_HOME', default='.repo') |
| 94 |
@click.option('--debug/--no-debug', default=False, |
| 95 |
envvar='REPO_DEBUG') |
| 96 |
@click.pass_context |
| 97 |
def cli(ctx, repo_home, debug): |
| 98 |
ctx.obj = Repo(repo_home, debug) |
| 99 |
``` |
| 100 |
|
| 101 |
Let's understand what this does. We create a group command which can |
| 102 |
have subcommands. When it is invoked, it will create an instance of a |
| 103 |
`Repo` class. This holds the state for our command line tool. In this |
| 104 |
case, it just remembers some parameters, but at this point it could also |
| 105 |
start loading configuration files and so on. |
| 106 |
|
| 107 |
This state object is then remembered by the context as {attr}`~Context.obj`. |
| 108 |
This is a special attribute where commands are supposed to remember what |
| 109 |
they need to pass on to their children. |
| 110 |
|
| 111 |
In order for this to work, we need to mark our function with |
| 112 |
{func}`pass_context`, because otherwise, the context object would be |
| 113 |
entirely hidden from us. |
| 114 |
|
| 115 |
### The First Child Command |
| 116 |
|
| 117 |
Let's add our first child command to it, the clone command: |
| 118 |
|
| 119 |
```python |
| 120 |
@cli.command() |
| 121 |
@click.argument('src') |
| 122 |
@click.argument('dest', required=False) |
| 123 |
def clone(src, dest): |
| 124 |
pass |
| 125 |
``` |
| 126 |
|
| 127 |
So now we have a clone command, but how do we get access to the repo? As |
| 128 |
you can imagine, one way is to use the {func}`pass_context` function which |
| 129 |
again will make our callback also get the context passed on which we |
| 130 |
memorized the repo. However, there is a second version of this decorator |
| 131 |
called {func}`pass_obj` which will just pass the stored object, (in our case |
| 132 |
the repo): |
| 133 |
|
| 134 |
```python |
| 135 |
@cli.command() |
| 136 |
@click.argument('src') |
| 137 |
@click.argument('dest', required=False) |
| 138 |
@click.pass_obj |
| 139 |
def clone(repo, src, dest): |
| 140 |
pass |
| 141 |
``` |
| 142 |
|
| 143 |
### Interleaved Commands |
| 144 |
|
| 145 |
While not relevant for the particular program we want to build, there is |
| 146 |
also quite good support for interleaving systems. Imagine for instance that |
| 147 |
there was a super cool plugin for our version control system that needed a |
| 148 |
lot of configuration and wanted to store its own configuration as |
| 149 |
{attr}`~Context.obj`. If we would then attach another command below that, |
| 150 |
we would all of a sudden get the plugin configuration instead of our repo |
| 151 |
object. |
| 152 |
|
| 153 |
One obvious way to remedy this is to store a reference to the repo in the |
| 154 |
plugin, but then a command needs to be aware that it's attached below such a |
| 155 |
plugin. |
| 156 |
|
| 157 |
There is a much better system that can be built by taking advantage of the |
| 158 |
linked nature of contexts. We know that the plugin context is linked to the |
| 159 |
context that created our repo. Because of that, we can start a search for |
| 160 |
the last level where the object stored by the context was a repo. |
| 161 |
|
| 162 |
Built-in support for this is provided by the {func}`make_pass_decorator` |
| 163 |
factory, which will create decorators for us that find objects (it |
| 164 |
internally calls into {meth}`Context.find_object`). In our case, we |
| 165 |
know that we want to find the closest `Repo` object, so let's make a |
| 166 |
decorator for this: |
| 167 |
|
| 168 |
```python |
| 169 |
pass_repo = click.make_pass_decorator(Repo) |
| 170 |
``` |
| 171 |
|
| 172 |
If we now use `pass_repo` instead of `pass_obj`, we will always get a |
| 173 |
repo instead of something else: |
| 174 |
|
| 175 |
```python |
| 176 |
@cli.command() |
| 177 |
@click.argument('src') |
| 178 |
@click.argument('dest', required=False) |
| 179 |
@pass_repo |
| 180 |
def clone(repo, src, dest): |
| 181 |
pass |
| 182 |
``` |
| 183 |
|
| 184 |
### Ensuring Object Creation |
| 185 |
|
| 186 |
The above example only works if there was an outer command that created a |
| 187 |
`Repo` object and stored it in the context. For some more advanced use |
| 188 |
cases, this might become a problem. The default behavior of |
| 189 |
{func}`make_pass_decorator` is to call {meth}`Context.find_object` |
| 190 |
which will find the object. If it can't find the object, |
| 191 |
{meth}`make_pass_decorator` will raise an error. |
| 192 |
The alternative behavior is to use {meth}`Context.ensure_object` |
| 193 |
which will find the object, and if it cannot find it, will create one and |
| 194 |
store it in the innermost context. This behavior can also be enabled for |
| 195 |
{func}`make_pass_decorator` by passing `ensure=True`: |
| 196 |
|
| 197 |
```python |
| 198 |
pass_repo = click.make_pass_decorator(Repo, ensure=True) |
| 199 |
``` |
| 200 |
|
| 201 |
In this case, the innermost context gets an object created if it is |
| 202 |
missing. This might replace objects being placed there earlier. In this |
| 203 |
case, the command stays executable, even if the outer command does not run. |
| 204 |
For this to work, the object type needs to have a constructor that accepts |
| 205 |
no arguments. |
| 206 |
|
| 207 |
As such it runs standalone: |
| 208 |
|
| 209 |
```python |
| 210 |
@click.command() |
| 211 |
@pass_repo |
| 212 |
def cp(repo): |
| 213 |
click.echo(isinstance(repo, Repo)) |
| 214 |
``` |
| 215 |
As you can see: |
| 216 |
|
| 217 |
```console |
| 218 |
$ cp |
| 219 |
True |
| 220 |
``` |
| 221 |
|
| 222 |
## Lazily Loading Subcommands |
| 223 |
|
| 224 |
Large CLIs and CLIs with slow imports may benefit from deferring the loading of |
| 225 |
subcommands. The interfaces which support this mode of use are |
| 226 |
{meth}`Group.list_commands` and {meth}`Group.get_command`. A custom |
| 227 |
{class}`Group` subclass can implement a lazy loader by storing extra data such |
| 228 |
that {meth}`Group.get_command` is responsible for running imports. |
| 229 |
|
| 230 |
Since the primary case for this is a {class}`Group` which loads its subcommands lazily, |
| 231 |
the following example shows a lazy-group implementation. |
| 232 |
|
| 233 |
```{warning} |
| 234 |
Lazy loading of python code can result in hard to track down bugs, circular imports |
| 235 |
in order-dependent codebases, and other surprising behaviors. It is recommended that |
| 236 |
this technique only be used in concert with testing which will at least run the |
| 237 |
`--help` on each subcommand. That will guarantee that each subcommand can be loaded |
| 238 |
successfully. |
| 239 |
``` |
| 240 |
|
| 241 |
### Defining the Lazy Group |
| 242 |
|
| 243 |
The following {class}`Group` subclass adds an attribute, `lazy_subcommands`, which |
| 244 |
stores a mapping from subcommand names to the information for importing them. |
| 245 |
|
| 246 |
|
| 247 |
```python |
| 248 |
# in lazy_group.py |
| 249 |
import importlib |
| 250 |
import click |
| 251 |
|
| 252 |
class 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 {} |
| 260 |
|
| 261 |
def list_commands(self, ctx): |
| 262 |
base = super().list_commands(ctx) |
| 263 |
lazy = sorted(self.lazy_subcommands.keys()) |
| 264 |
return base + lazy |
| 265 |
|
| 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) |
| 270 |
|
| 271 |
def _lazy_load(self, cmd_name): |
| 272 |
# lazily loading a command, first get the module name and attribute name |
| 273 |
import_path = self.lazy_subcommands[cmd_name] |
| 274 |
modname, cmd_object_name = import_path.rsplit(".", 1) |
| 275 |
# do the import |
| 276 |
mod = importlib.import_module(modname) |
| 277 |
# get the Command object from that module |
| 278 |
cmd_object = getattr(mod, cmd_object_name) |
| 279 |
# check the result to make debugging easier |
| 280 |
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_object |
| 286 |
``` |
| 287 |
|
| 288 |
### Using LazyGroup To Define a CLI |
| 289 |
|
| 290 |
With `LazyGroup` defined, it's now possible to write a group which lazily loads its |
| 291 |
subcommands like so: |
| 292 |
|
| 293 |
```python |
| 294 |
# in main.py |
| 295 |
import click |
| 296 |
from lazy_group import LazyGroup |
| 297 |
|
| 298 |
@click.group( |
| 299 |
cls=LazyGroup, |
| 300 |
lazy_subcommands={"foo": "foo.cli", "bar": "bar.cli"}, |
| 301 |
help="main CLI command for lazy example", |
| 302 |
) |
| 303 |
def cli(): |
| 304 |
pass |
| 305 |
``` |
| 306 |
|
| 307 |
```python |
| 308 |
# in foo.py |
| 309 |
import click |
| 310 |
|
| 311 |
@click.group(help="foo command for lazy example") |
| 312 |
def cli(): |
| 313 |
pass |
| 314 |
``` |
| 315 |
|
| 316 |
```python |
| 317 |
# in bar.py |
| 318 |
import click |
| 319 |
from lazy_group import LazyGroup |
| 320 |
|
| 321 |
@click.group( |
| 322 |
cls=LazyGroup, |
| 323 |
lazy_subcommands={"baz": "baz.cli"}, |
| 324 |
help="bar command for lazy example", |
| 325 |
) |
| 326 |
def cli(): |
| 327 |
pass |
| 328 |
``` |
| 329 |
|
| 330 |
```python |
| 331 |
# in baz.py |
| 332 |
import click |
| 333 |
|
| 334 |
@click.group(help="baz command for lazy example") |
| 335 |
def cli(): |
| 336 |
pass |
| 337 |
``` |
| 338 |
|
| 339 |
### What triggers Lazy Loading? |
| 340 |
|
| 341 |
There are several events which may trigger lazy loading by running the |
| 342 |
{meth}`Group.get_command` function. |
| 343 |
Some are intuititve, and some are less so. |
| 344 |
|
| 345 |
All cases are described with respect to the above example, assuming the main program |
| 346 |
name is `cli`. |
| 347 |
|
| 348 |
1. Command resolution. If a user runs `cli bar baz`, this must first resolve `bar`, |
| 349 |
and then resolve `baz`. Each subcommand resolution step does a lazy load. |
| 350 |
2. Helptext rendering. In order to get the short help description of subcommands, |
| 351 |
`cli --help` will load `foo` and `bar`. Note that it will still not load |
| 352 |
`baz`. |
| 353 |
3. Shell completion. In order to get the subcommands of a lazy command, `cli <TAB>` |
| 354 |
will need to resolve the subcommands of `cli`. This process will trigger the lazy |
| 355 |
loads. |
| 356 |
|
| 357 |
### Further Deferring Imports |
| 358 |
|
| 359 |
It is possible to make the process even lazier, but it is generally more difficult the |
| 360 |
more you want to defer work. |
| 361 |
|
| 362 |
For example, subcommands could be represented as a custom {class}`Command` subclass |
| 363 |
which defers importing the command until it is invoked, but which provides |
| 364 |
{meth}`Command.get_short_help_str` in order to support completions and helptext. |
| 365 |
More simply, commands can be constructed whose callback functions defer any actual work |
| 366 |
until after an import. |
| 367 |
|
| 368 |
This command definition provides `foo`, but any of the work associated with importing |
| 369 |
the "real" callback function is deferred until invocation time: |
| 370 |
|
| 371 |
```{eval-rst} |
| 372 |
.. click:example:: |
| 373 |
|
| 374 |
@click.command() |
| 375 |
@click.option("-n", type=int) |
| 376 |
@click.option("-w", type=str) |
| 377 |
def foo(n, w): |
| 378 |
from mylibrary import foo_concrete |
| 379 |
|
| 380 |
foo_concrete(n, w) |
| 381 |
``` |
| 382 |
|
| 383 |
Because Click builds helptext and usage info from options, arguments, and command |
| 384 |
attributes, it has no awareness that the underlying function is in any way handling a |
| 385 |
deferred import. Therefore, all Click-provided utilities and functionality will work |
| 386 |
as normal on such a command. |