Skip to content
Myr

complex.md

This file

Path

docs/complex.md

385 lines · 12.6 KiB · Markdown

Last changed by

refactor from rest to mystdenuowebbefore adoptionc83fd82

History of this file

Take it

refactor from rest to mystdenuowebbefore adoptionc83fd82

line 1why, one step back
1(complex-guide)=

rename from .rst to .mddenuowebbefore adoption3df7be3

line 2why, one step back
2

refactor from rest to mystdenuowebbefore adoptionc83fd82

line 3why, one step back
3# Complex Applications

rename from .rst to .mddenuowebbefore adoption3df7be3

line 4why, one step back
4

refactor from rest to mystdenuowebbefore adoptionc83fd82

lines 5–6why, one step back
5```{currentmodule} click
6```

rename from .rst to .mddenuowebbefore adoption3df7be3

lines 7–18why, one step back
7
8Click 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 will11have realized that it provides a command line utility, but so does Celery.12When using Celery with Django, there are two tools that need to interact with13each other and be cross-configured.1415In 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.18

refactor from rest to mystdenuowebbefore adoptionc83fd82

lines 19–24why, one step back
19```{contents}
20---21depth: 122local: true23---24```

rename from .rst to .mddenuowebbefore adoption3df7be3

line 25why, one step back
25

refactor from rest to mystdenuowebbefore adoptionc83fd82

line 26why, one step back
26## Basic Concepts

rename from .rst to .mddenuowebbefore adoption3df7be3

lines 27–30why, one step back
27
28To understand how this works, you need to understand two concepts: contexts29and the calling convention.30

refactor from rest to mystdenuowebbefore adoptionc83fd82

line 31why, one step back
31### Contexts

rename from .rst to .mddenuowebbefore adoption3df7be3

line 32why, one step back
32

refactor from rest to mystdenuowebbefore adoptionc83fd82

line 33why, one step back
33Whenever a Click command is executed, a {class}`Context` object is created

rename from .rst to .mddenuowebbefore adoption3df7be3

lines 34–49why, one step back
34which holds state for this particular invocation. It remembers parsed
35parameters, 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.3839Context objects build a linked list until they hit the top one. Each context40is linked to a parent context. This allows a command to work below41another command and store its own information there without having to be42afraid of altering up the state of the parent command.4344Because the parent data is available, however, it is possible to navigate to45it if needed.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.49

refactor from rest to mystdenuowebbefore adoptionc83fd82

line 50why, one step back
50### Calling Convention

rename from .rst to .mddenuowebbefore adoption3df7be3

lines 51–54why, one step back
51
52When 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 itself

refactor from rest to mystdenuowebbefore adoptionc83fd82

line 55why, one step back
55with {func}`pass_context`.

rename from .rst to .mddenuowebbefore adoption3df7be3

lines 56–58why, one step back
56
57So 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 itself

refactor from rest to mystdenuowebbefore adoptionc83fd82

line 59why, one step back
59provides a helper function ({meth}`Context.invoke`) which can do this for

rename from .rst to .mddenuowebbefore adoption3df7be3

lines 60–62why, one step back
60you. It accepts the callback as first argument and then invokes the
61function correctly.62

refactor from rest to mystdenuowebbefore adoptionc83fd82

line 63why, one step back
63## Building a Git Clone

rename from .rst to .mddenuowebbefore adoption3df7be3

lines 64–69why, one step back
64
65In 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.69

refactor from rest to mystdenuowebbefore adoptionc83fd82

line 70why, one step back
70### The Root Command

rename from .rst to .mddenuowebbefore adoption3df7be3

lines 71–72why, one step back
71
72At the top level, we need a group that can hold all our commands. In this

refactor from rest to mystdenuowebbefore adoptionc83fd82

line 73why, one step back
73case, we use the basic {func}`click.group` which allows us to register

rename from .rst to .mddenuowebbefore adoption3df7be3

lines 74–78why, one step back
74other Click commands below it.
7576For this command, we also want to accept some parameters that configure the77state of our tool:78

refactor from rest to mystdenuowebbefore adoptionc83fd82

line 79why, one step back
79```{eval-rst}

rename from .rst to .mddenuowebbefore adoption3df7be3

lines 80–98why, one step back
80.. click:example::
8182 import os83 import click848586 class Repo(object):87 def __init__(self, home=None, debug=False):88 self.home = os.path.abspath(home or '.')89 self.debug = debug909192 @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_context97 def cli(ctx, repo_home, debug):98 ctx.obj = Repo(repo_home, debug)

refactor from rest to mystdenuowebbefore adoptionc83fd82

line 99why, one step back
99```

rename from .rst to .mddenuowebbefore adoption3df7be3

lines 100–102why, one step back
100
101Let's understand what this does. We create a group command which can102have subcommands. When it is invoked, it will create an instance of a

refactor from rest to mystdenuowebbefore adoptionc83fd82

line 103why, one step back
103`Repo` class. This holds the state for our command line tool. In this

rename from .rst to .mddenuowebbefore adoption3df7be3

lines 104–106why, one step back
104case, it just remembers some parameters, but at this point it could also
105start loading configuration files and so on.106

refactor from rest to mystdenuowebbefore adoptionc83fd82

line 107why, one step back
107This state object is then remembered by the context as {attr}`~Context.obj`.

rename from .rst to .mddenuowebbefore adoption3df7be3

lines 108–111why, one step back
108This is a special attribute where commands are supposed to remember what
109they need to pass on to their children.110111In order for this to work, we need to mark our function with

refactor from rest to mystdenuowebbefore adoptionc83fd82

line 112why, one step back
112{func}`pass_context`, because otherwise, the context object would be

rename from .rst to .mddenuowebbefore adoption3df7be3

lines 113–114why, one step back
113entirely hidden from us.
114

refactor from rest to mystdenuowebbefore adoptionc83fd82

line 115why, one step back
115### The First Child Command

rename from .rst to .mddenuowebbefore adoption3df7be3

lines 116–118why, one step back
116
117Let's add our first child command to it, the clone command:118

refactor from rest to mystdenuowebbefore adoptionc83fd82

lines 119–125why, one step back
119```python
120@cli.command()121@click.argument('src')122@click.argument('dest', required=False)123def clone(src, dest):124 pass125```

rename from .rst to .mddenuowebbefore adoption3df7be3

lines 126–127why, one step back
126
127So now we have a clone command, but how do we get access to the repo? As

refactor from rest to mystdenuowebbefore adoptionc83fd82

line 128why, one step back
128you can imagine, one way is to use the {func}`pass_context` function which

rename from .rst to .mddenuowebbefore adoption3df7be3

lines 129–130why, one step back
129again will make our callback also get the context passed on which we
130memorized the repo. However, there is a second version of this decorator

refactor from rest to mystdenuowebbefore adoptionc83fd82

line 131why, one step back
131called {func}`pass_obj` which will just pass the stored object, (in our case

rename from .rst to .mddenuowebbefore adoption3df7be3

lines 132–133why, one step back
132the repo):
133

refactor from rest to mystdenuowebbefore adoptionc83fd82

lines 134–141why, one step back
134```python
135@cli.command()136@click.argument('src')137@click.argument('dest', required=False)138@click.pass_obj139def clone(repo, src, dest):140 pass141```

rename from .rst to .mddenuowebbefore adoption3df7be3

line 142why, one step back
142

refactor from rest to mystdenuowebbefore adoptionc83fd82

line 143why, one step back
143### Interleaved Commands

rename from .rst to .mddenuowebbefore adoption3df7be3

lines 144–148why, one step back
144
145While 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 as

refactor from rest to mystdenuowebbefore adoptionc83fd82

line 149why, one step back
149{attr}`~Context.obj`. If we would then attach another command below that,

rename from .rst to .mddenuowebbefore adoption3df7be3

lines 150–161why, one step back
150we would all of a sudden get the plugin configuration instead of our repo
151object.152153One obvious way to remedy this is to store a reference to the repo in the154plugin, but then a command needs to be aware that it's attached below such a155plugin.156157There is a much better system that can be built by taking advantage of the158linked 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.161

refactor from rest to mystdenuowebbefore adoptionc83fd82

line 162why, one step back
162Built-in support for this is provided by the {func}`make_pass_decorator`

rename from .rst to .mddenuowebbefore adoption3df7be3

line 163why, one step back
163factory, which will create decorators for us that find objects (it

refactor from rest to mystdenuowebbefore adoptionc83fd82

lines 164–165why, one step back
164internally calls into {meth}`Context.find_object`). In our case, we
165know that we want to find the closest `Repo` object, so let's make a

rename from .rst to .mddenuowebbefore adoption3df7be3

lines 166–167why, one step back
166decorator for this:
167

refactor from rest to mystdenuowebbefore adoptionc83fd82

lines 168–170why, one step back
168```python
169pass_repo = click.make_pass_decorator(Repo)170```

rename from .rst to .mddenuowebbefore adoption3df7be3

line 171why, one step back
171

refactor from rest to mystdenuowebbefore adoptionc83fd82

line 172why, one step back
172If we now use `pass_repo` instead of `pass_obj`, we will always get a

rename from .rst to .mddenuowebbefore adoption3df7be3

lines 173–174why, one step back
173repo instead of something else:
174

refactor from rest to mystdenuowebbefore adoptionc83fd82

lines 175–182why, one step back
175```python
176@cli.command()177@click.argument('src')178@click.argument('dest', required=False)179@pass_repo180def clone(repo, src, dest):181 pass182```

rename from .rst to .mddenuowebbefore adoption3df7be3

line 183why, one step back
183

refactor from rest to mystdenuowebbefore adoptionc83fd82

line 184why, one step back
184### Ensuring Object Creation

rename from .rst to .mddenuowebbefore adoption3df7be3

lines 185–186why, one step back
185
186The above example only works if there was an outer command that created a

refactor from rest to mystdenuowebbefore adoptionc83fd82

line 187why, one step back
187`Repo` object and stored it in the context. For some more advanced use

rename from .rst to .mddenuowebbefore adoption3df7be3

line 188why, one step back
188cases, this might become a problem. The default behavior of

refactor from rest to mystdenuowebbefore adoptionc83fd82

line 189why, one step back
189{func}`make_pass_decorator` is to call {meth}`Context.find_object`

rename from .rst to .mddenuowebbefore adoption3df7be3

line 190why, one step back
190which will find the object. If it can't find the object,

refactor from rest to mystdenuowebbefore adoptionc83fd82

lines 191–192why, one step back
191{meth}`make_pass_decorator` will raise an error.
192The alternative behavior is to use {meth}`Context.ensure_object`

rename from .rst to .mddenuowebbefore adoption3df7be3

lines 193–194why, one step back
193which will find the object, and if it cannot find it, will create one and
194store it in the innermost context. This behavior can also be enabled for

refactor from rest to mystdenuowebbefore adoptionc83fd82

line 195why, one step back
195{func}`make_pass_decorator` by passing `ensure=True`:

rename from .rst to .mddenuowebbefore adoption3df7be3

line 196why, one step back
196

refactor from rest to mystdenuowebbefore adoptionc83fd82

lines 197–199why, one step back
197```python
198pass_repo = click.make_pass_decorator(Repo, ensure=True)199```

rename from .rst to .mddenuowebbefore adoption3df7be3

lines 200–208why, one step back
200
201In 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:208

refactor from rest to mystdenuowebbefore adoptionc83fd82

line 209why, one step back
209```python

rename from .rst to .mddenuowebbefore adoption3df7be3

lines 210–213why, one step back
210 @click.command()
211 @pass_repo212 def cp(repo):213 click.echo(isinstance(repo, Repo))

refactor from rest to mystdenuowebbefore adoptionc83fd82

line 214why, one step back
214```

rename from .rst to .mddenuowebbefore adoption3df7be3

lines 215–216why, one step back
215As you can see:
216

refactor from rest to mystdenuowebbefore adoptionc83fd82

lines 217–220why, one step back
217```console
218$ cp219True220```

rename from .rst to .mddenuowebbefore adoption3df7be3

line 221why, one step back
221

refactor from rest to mystdenuowebbefore adoptionc83fd82

line 222why, one step back
222## Lazily Loading Subcommands

rename from .rst to .mddenuowebbefore adoption3df7be3

lines 223–225why, one step back
223
224Large CLIs and CLIs with slow imports may benefit from deferring the loading of225subcommands. The interfaces which support this mode of use are

refactor from rest to mystdenuowebbefore adoptionc83fd82

lines 226–228why, one step back
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 such228that {meth}`Group.get_command` is responsible for running imports.

rename from .rst to .mddenuowebbefore adoption3df7be3

line 229why, one step back
229

refactor from rest to mystdenuowebbefore adoptionc83fd82

line 230why, one step back
230Since the primary case for this is a {class}`Group` which loads its subcommands lazily,

rename from .rst to .mddenuowebbefore adoption3df7be3

lines 231–232why, one step back
231the following example shows a lazy-group implementation.
232

refactor from rest to mystdenuowebbefore adoptionc83fd82

lines 233–239why, one step back
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```

rename from .rst to .mddenuowebbefore adoption3df7be3

line 240why, one step back
240

refactor from rest to mystdenuowebbefore adoptionc83fd82

line 241why, one step back
241### Defining the Lazy Group

rename from .rst to .mddenuowebbefore adoption3df7be3

line 242why, one step back
242

refactor from rest to mystdenuowebbefore adoptionc83fd82

line 243why, one step back
243The following {class}`Group` subclass adds an attribute, `lazy_subcommands`, which

rename from .rst to .mddenuowebbefore adoption3df7be3

lines 244–246why, one step back
244stores a mapping from subcommand names to the information for importing them.
245246

refactor from rest to mystdenuowebbefore adoptionc83fd82

lines 247–250why, one step back
247```python
248# in lazy_group.py249import importlib250import click

rename from .rst to .mddenuowebbefore adoption3df7be3

line 251why, one step back
251

refactor from rest to mystdenuowebbefore adoptionc83fd82

lines 252–259why, one step back
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 {}

rename from .rst to .mddenuowebbefore adoption3df7be3

line 260why, one step back
260

refactor from rest to mystdenuowebbefore adoptionc83fd82

lines 261–264why, one step back
261 def list_commands(self, ctx):
262 base = super().list_commands(ctx)263 lazy = sorted(self.lazy_subcommands.keys())264 return base + lazy

rename from .rst to .mddenuowebbefore adoption3df7be3

line 265why, one step back
265

refactor from rest to mystdenuowebbefore adoptionc83fd82

lines 266–269why, one step back
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)

rename from .rst to .mddenuowebbefore adoption3df7be3

line 270why, one step back
270

refactor from rest to mystdenuowebbefore adoptionc83fd82

lines 271–286why, one step back
271 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```

rename from .rst to .mddenuowebbefore adoption3df7be3

line 287why, one step back
287

refactor from rest to mystdenuowebbefore adoptionc83fd82

line 288why, one step back
288### Using LazyGroup To Define a CLI

rename from .rst to .mddenuowebbefore adoption3df7be3

line 289why, one step back
289

refactor from rest to mystdenuowebbefore adoptionc83fd82

line 290why, one step back
290With `LazyGroup` defined, it's now possible to write a group which lazily loads its

rename from .rst to .mddenuowebbefore adoption3df7be3

lines 291–292why, one step back
291subcommands like so:
292

refactor from rest to mystdenuowebbefore adoptionc83fd82

lines 293–296why, one step back
293```python
294# in main.py295import click296from lazy_group import LazyGroup

rename from .rst to .mddenuowebbefore adoption3df7be3

line 297why, one step back
297

refactor from rest to mystdenuowebbefore adoptionc83fd82

lines 298–305why, one step back
298@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```

rename from .rst to .mddenuowebbefore adoption3df7be3

line 306why, one step back
306

refactor from rest to mystdenuowebbefore adoptionc83fd82

lines 307–309why, one step back
307```python
308# in foo.py309import click

rename from .rst to .mddenuowebbefore adoption3df7be3

line 310why, one step back
310

refactor from rest to mystdenuowebbefore adoptionc83fd82

lines 311–318why, one step back
311@click.group(help="foo command for lazy example")
312def cli():313 pass314```315```python316# in bar.py317import click318from lazy_group import LazyGroup

rename from .rst to .mddenuowebbefore adoption3df7be3

line 319why, one step back
319

refactor from rest to mystdenuowebbefore adoptionc83fd82

lines 320–327why, one step back
320@click.group(
321 cls=LazyGroup,322 lazy_subcommands={"baz": "baz.cli"},323 help="bar command for lazy example",324)325def cli():326 pass327```

rename from .rst to .mddenuowebbefore adoption3df7be3

line 328why, one step back
328

refactor from rest to mystdenuowebbefore adoptionc83fd82

lines 329–331why, one step back
329```python
330# in baz.py331import click

rename from .rst to .mddenuowebbefore adoption3df7be3

line 332why, one step back
332

refactor from rest to mystdenuowebbefore adoptionc83fd82

lines 333–336why, one step back
333@click.group(help="baz command for lazy example")
334def cli():335 pass336```

rename from .rst to .mddenuowebbefore adoption3df7be3

line 337why, one step back
337

refactor from rest to mystdenuowebbefore adoptionc83fd82

line 338why, one step back
338### What triggers Lazy Loading?

rename from .rst to .mddenuowebbefore adoption3df7be3

lines 339–340why, one step back
339
340There are several events which may trigger lazy loading by running the

refactor from rest to mystdenuowebbefore adoptionc83fd82

line 341why, one step back
341{meth}`Group.get_command` function.

rename from .rst to .mddenuowebbefore adoption3df7be3

lines 342–343why, one step back
342Some are intuititve, and some are less so.
343

refactor from rest to mystdenuowebbefore adoptionc83fd82

lines 344–345why, one step back
344All cases are described with respect to the above example, assuming the main progra
345name is `cli`.

rename from .rst to .mddenuowebbefore adoption3df7be3

line 346why, one step back
346

refactor from rest to mystdenuowebbefore adoptionc83fd82

lines 347–348why, one step back
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.

rename from .rst to .mddenuowebbefore adoption3df7be3

line 349why, one step back
3492. Helptext rendering. In order to get the short help description of subcommands,

refactor from rest to mystdenuowebbefore adoptionc83fd82

lines 350–353why, one step back
350 `cli --help` will load `foo` and `bar`. Note that it will still not load
351 `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 lazy

rename from .rst to .mddenuowebbefore adoption3df7be3

lines 354–355why, one step back
354 loads.
355

refactor from rest to mystdenuowebbefore adoptionc83fd82

line 356why, one step back
356### Further Deferring Imports

rename from .rst to .mddenuowebbefore adoption3df7be3

lines 357–360why, one step back
357
358It is possible to make the process even lazier, but it is generally more difficult the359more you want to defer work.360

refactor from rest to mystdenuowebbefore adoptionc83fd82

line 361why, one step back
361For example, subcommands could be represented as a custom {class}`Command` subclass

rename from .rst to .mddenuowebbefore adoption3df7be3

line 362why, one step back
362which defers importing the command until it is invoked, but which provides

refactor from rest to mystdenuowebbefore adoptionc83fd82

line 363why, one step back
363{meth}`Command.get_short_help_str` in order to support completions and helptext.

rename from .rst to .mddenuowebbefore adoption3df7be3

lines 364–366why, one step back
364More simply, commands can be constructed whose callback functions defer any actual work
365until after an import.366

refactor from rest to mystdenuowebbefore adoptionc83fd82

line 367why, one step back
367This command definition provides `foo`, but any of the work associated with importing

rename from .rst to .mddenuowebbefore adoption3df7be3

lines 368–369why, one step back
368the "real" callback function is deferred until invocation time:
369

refactor from rest to mystdenuowebbefore adoptionc83fd82

line 370why, one step back
370```{eval-rst}

rename from .rst to .mddenuowebbefore adoption3df7be3

lines 371–379why, one step back
371.. click:example::
372373 @click.command()374 @click.option("-n", type=int)375 @click.option("-w", type=str)376 def foo(n, w):377 from mylibrary import foo_concrete378379 foo_concrete(n, w)

refactor from rest to mystdenuowebbefore adoptionc83fd82

line 380why, one step back
380```

rename from .rst to .mddenuowebbefore adoption3df7be3

lines 381–385why, one step back
381
382Because 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 work385as normal on such a command.