| 1 |
# Advanced Groups and Context |
| 2 |
|
| 3 |
```{currentmodule} click |
| 4 |
``` |
| 5 |
|
| 6 |
In addition to the capabilities covered in the previous section, Groups have |
| 7 |
more advanced capabilities that leverage the Context. |
| 8 |
|
| 9 |
```{contents} |
| 10 |
--- |
| 11 |
depth: 1 |
| 12 |
local: true |
| 13 |
--- |
| 14 |
``` |
| 15 |
|
| 16 |
## Callback Invocation |
| 17 |
|
| 18 |
For a regular command, the callback is executed whenever the command runs. |
| 19 |
If the script is the only command, it will always fire (unless a parameter |
| 20 |
callback prevents it. This for instance happens if someone passes |
| 21 |
`--help` to the script). |
| 22 |
|
| 23 |
For groups, the situation looks different. In this case, the callback fires |
| 24 |
whenever a subcommand fires. What this means in practice is that an outer |
| 25 |
command runs when an inner command runs: |
| 26 |
|
| 27 |
```{eval-rst} |
| 28 |
.. click:example:: |
| 29 |
|
| 30 |
@click.group() |
| 31 |
@click.option('--debug/--no-debug', default=False) |
| 32 |
def cli(debug): |
| 33 |
click.echo(f"Debug mode is {'on' if debug else 'off'}") |
| 34 |
|
| 35 |
@cli.command() # @cli, not @click! |
| 36 |
def sync(): |
| 37 |
click.echo('Syncing') |
| 38 |
|
| 39 |
Here is what this looks like: |
| 40 |
|
| 41 |
.. click:run:: |
| 42 |
|
| 43 |
invoke(cli, prog_name='tool.py') |
| 44 |
println() |
| 45 |
invoke(cli, prog_name='tool.py', args=['--debug', 'sync']) |
| 46 |
``` |
| 47 |
|
| 48 |
## Nested Handling and Contexts |
| 49 |
|
| 50 |
As you can see from the earlier example, the basic command group accepts a |
| 51 |
debug argument which is passed to its callback, but not to the sync |
| 52 |
command itself. The sync command only accepts its own arguments. |
| 53 |
|
| 54 |
This allows tools to act completely independent of each other, but how |
| 55 |
does one command talk to a nested one? The answer to this is the |
| 56 |
{class}`Context`. |
| 57 |
|
| 58 |
Each time a command is invoked, a new context is created and linked with the |
| 59 |
parent context. Normally, you can't see these contexts, but they are |
| 60 |
there. Contexts are passed to parameter callbacks together with the |
| 61 |
value automatically. Commands can also ask for the context to be passed |
| 62 |
by marking themselves with the {func}`pass_context` decorator. In that |
| 63 |
case, the context is passed as first argument. |
| 64 |
|
| 65 |
The context can also carry a program specified object that can be |
| 66 |
used for the program's purposes. What this means is that you can build a |
| 67 |
script like this: |
| 68 |
|
| 69 |
```{eval-rst} |
| 70 |
.. click:example:: |
| 71 |
|
| 72 |
@click.group() |
| 73 |
@click.option('--debug/--no-debug', default=False) |
| 74 |
@click.pass_context |
| 75 |
def cli(ctx, debug): |
| 76 |
# ensure that ctx.obj exists and is a dict (in case `cli()` is called |
| 77 |
# by means other than the `if` block below) |
| 78 |
ctx.ensure_object(dict) |
| 79 |
|
| 80 |
ctx.obj['DEBUG'] = debug |
| 81 |
|
| 82 |
@cli.command() |
| 83 |
@click.pass_context |
| 84 |
def sync(ctx): |
| 85 |
click.echo(f"Debug is {'on' if ctx.obj['DEBUG'] else 'off'}") |
| 86 |
|
| 87 |
if __name__ == '__main__': |
| 88 |
cli(obj={}) |
| 89 |
``` |
| 90 |
|
| 91 |
If the object is provided, each context will pass the object onwards to |
| 92 |
its children, but at any level a context's object can be overridden. To |
| 93 |
reach to a parent, `context.parent` can be used. |
| 94 |
|
| 95 |
In addition to that, instead of passing an object down, nothing stops the |
| 96 |
application from modifying global state. For instance, you could just flip |
| 97 |
a global `DEBUG` variable and be done with it. |
| 98 |
|
| 99 |
## Decorating Commands |
| 100 |
|
| 101 |
As you have seen in the earlier example, a decorator can change how a |
| 102 |
command is invoked. What actually happens behind the scenes is that |
| 103 |
callbacks are always invoked through the {meth}`Context.invoke` method |
| 104 |
which automatically invokes a command correctly (by either passing the |
| 105 |
context or not). |
| 106 |
|
| 107 |
This is very useful when you want to write custom decorators. For |
| 108 |
instance, a common pattern would be to configure an object representing |
| 109 |
state and then storing it on the context and then to use a custom |
| 110 |
decorator to find the most recent object of this sort and pass it as first |
| 111 |
argument. |
| 112 |
|
| 113 |
For instance, the {func}`pass_obj` decorator can be implemented like this: |
| 114 |
|
| 115 |
```{eval-rst} |
| 116 |
.. click:example:: |
| 117 |
|
| 118 |
from functools import update_wrapper |
| 119 |
|
| 120 |
def pass_obj(f): |
| 121 |
@click.pass_context |
| 122 |
def new_func(ctx, *args, **kwargs): |
| 123 |
return ctx.invoke(f, ctx.obj, *args, **kwargs) |
| 124 |
return update_wrapper(new_func, f) |
| 125 |
``` |
| 126 |
|
| 127 |
The {meth}`Context.invoke` command will automatically invoke the function |
| 128 |
in the correct way, so the function will either be called with`f(ctx, |
| 129 |
obj)` or `f(obj)` depending on whether or not it itself is decorated with |
| 130 |
{func}`pass_context`. |
| 131 |
|
| 132 |
This is a very powerful concept that can be used to build very complex |
| 133 |
nested applications; see {ref}`complex-guide` for more information. |
| 134 |
|
| 135 |
(command-chaining)= |
| 136 |
|
| 137 |
## Command Chaining |
| 138 |
|
| 139 |
It is useful to invoke more than one subcommand in one call. For example, |
| 140 |
`my-app validate build upload` would invoke `validate`, then `build`, then |
| 141 |
`upload`. To implement this, pass `chain=True` when creating a group. |
| 142 |
|
| 143 |
```{eval-rst} |
| 144 |
.. click:example:: |
| 145 |
|
| 146 |
@click.group(chain=True) |
| 147 |
def cli(): |
| 148 |
pass |
| 149 |
|
| 150 |
@cli.command('validate') |
| 151 |
def validate(): |
| 152 |
click.echo('validate') |
| 153 |
|
| 154 |
@cli.command('build') |
| 155 |
def build(): |
| 156 |
click.echo('build') |
| 157 |
|
| 158 |
You can invoke it like this: |
| 159 |
|
| 160 |
.. click:run:: |
| 161 |
|
| 162 |
invoke(cli, prog_name='my-app', args=['validate', 'build']) |
| 163 |
``` |
| 164 |
|
| 165 |
When using chaining, there are a few restrictions: |
| 166 |
|
| 167 |
- Only the last command may use `nargs=-1` on an argument, otherwise the |
| 168 |
parser will not be able to find further commands. |
| 169 |
- It is not possible to nest groups below a chain group. |
| 170 |
- On the command line, options must be specified before arguments for each |
| 171 |
command in the chain. |
| 172 |
- The {attr}`Context.invoked_subcommand` attribute will be `'*'` because the |
| 173 |
parser doesn't know the full list of commands that will run yet. |
| 174 |
|
| 175 |
(command-pipelines)= |
| 176 |
|
| 177 |
## Command Pipelines |
| 178 |
|
| 179 |
When using chaining, a common pattern is to have each command process the |
| 180 |
result of the previous command. |
| 181 |
|
| 182 |
A straightforward way to do this is to use {func}`make_pass_decorator` to pass |
| 183 |
a context object to each command, and store and read the data on that object. |
| 184 |
|
| 185 |
```{eval-rst} |
| 186 |
.. click:example:: |
| 187 |
|
| 188 |
pass_ns = click.make_pass_decorator(dict, ensure=True) |
| 189 |
|
| 190 |
@click.group(chain=True) |
| 191 |
@click.argument("name") |
| 192 |
@pass_ns |
| 193 |
def cli(ns, name): |
| 194 |
ns["name"] = name |
| 195 |
|
| 196 |
@cli.command |
| 197 |
@pass_ns |
| 198 |
def lower(ns): |
| 199 |
ns["name"] = ns["name"].lower() |
| 200 |
|
| 201 |
@cli.command |
| 202 |
@pass_ns |
| 203 |
def show(ns): |
| 204 |
click.echo(ns["name"]) |
| 205 |
|
| 206 |
.. click:run:: |
| 207 |
|
| 208 |
invoke(cli, prog_name="process", args=["Click", "show", "lower", "show"]) |
| 209 |
``` |
| 210 |
|
| 211 |
Another way to do this is to collect data returned by each command, then process |
| 212 |
it at the end of the chain. Use the group's {meth}`~Group.result_callback` |
| 213 |
decorator to register a function that is called after the chain is finished. It |
| 214 |
is passed the list of return values as well as any parameters registered on the |
| 215 |
group. |
| 216 |
|
| 217 |
A command can return anything, including a function. Here's an example of that, |
| 218 |
where each subcommand creates a function that processes the input, then the |
| 219 |
result callback calls each function. The command takes a file, processes each |
| 220 |
line, then outputs it. If no subcommands are given, it outputs the contents |
| 221 |
of the file unchanged. |
| 222 |
|
| 223 |
```python |
| 224 |
@click.group(chain=True, invoke_without_command=True) |
| 225 |
@click.argument("fin", type=click.File("r")) |
| 226 |
def cli(fin): |
| 227 |
pass |
| 228 |
|
| 229 |
@cli.result_callback() |
| 230 |
def process_pipeline(processors, fin): |
| 231 |
iterator = (x.rstrip("\r\n") for x in input) |
| 232 |
|
| 233 |
for processor in processors: |
| 234 |
iterator = processor(iterator) |
| 235 |
|
| 236 |
for item in iterator: |
| 237 |
click.echo(item) |
| 238 |
|
| 239 |
@cli.command("upper") |
| 240 |
def make_uppercase(): |
| 241 |
def processor(iterator): |
| 242 |
for line in iterator: |
| 243 |
yield line.upper() |
| 244 |
return processor |
| 245 |
|
| 246 |
@cli.command("lower") |
| 247 |
def make_lowercase(): |
| 248 |
def processor(iterator): |
| 249 |
for line in iterator: |
| 250 |
yield line.lower() |
| 251 |
return processor |
| 252 |
|
| 253 |
@cli.command("strip") |
| 254 |
def make_strip(): |
| 255 |
def processor(iterator): |
| 256 |
for line in iterator: |
| 257 |
yield line.strip() |
| 258 |
return processor |
| 259 |
``` |
| 260 |
|
| 261 |
That's a lot in one go, so let's go through it step by step. |
| 262 |
|
| 263 |
1. The first thing is to make a {func}`group` that is chainable. In |
| 264 |
addition to that we also instruct Click to invoke even if no |
| 265 |
subcommand is defined. If this would not be done, then invoking an |
| 266 |
empty pipeline would produce the help page instead of running the |
| 267 |
result callbacks. |
| 268 |
2. The next thing we do is to register a result callback on our group. |
| 269 |
This callback will be invoked with an argument which is the list of |
| 270 |
all return values of all subcommands and then the same keyword |
| 271 |
parameters as our group itself. This means we can access the input |
| 272 |
file easily there without having to use the context object. |
| 273 |
3. In this result callback we create an iterator of all the lines in the |
| 274 |
input file and then pass this iterator through all the returned |
| 275 |
callbacks from all subcommands and finally we print all lines to |
| 276 |
stdout. |
| 277 |
|
| 278 |
After that point we can register as many subcommands as we want and each |
| 279 |
subcommand can return a processor function to modify the stream of lines. |
| 280 |
|
| 281 |
One important thing of note is that Click shuts down the context after |
| 282 |
each callback has been run. This means that for instance file types |
| 283 |
cannot be accessed in the `processor` functions as the files will already |
| 284 |
be closed there. This limitation is unlikely to change because it would |
| 285 |
make resource handling much more complicated. For such it's recommended |
| 286 |
to not use the file type and manually open the file through |
| 287 |
{func}`open_file`. |
| 288 |
|
| 289 |
For a more complex example that also improves upon handling of the pipelines, |
| 290 |
see the [imagepipe example](https://github.com/pallets/click/tree/main/examples/imagepipe) |
| 291 |
in the Click repository. It implements a pipeline based image editing tool |
| 292 |
that has a nice internal structure. |
| 293 |
|
| 294 |
## Overriding Defaults |
| 295 |
|
| 296 |
By default, the default value for a parameter is pulled from the |
| 297 |
`default` flag that is provided when it's defined, but that's not the |
| 298 |
only place defaults can be loaded from. The other place is the |
| 299 |
{attr}`Context.default_map` (a dictionary) on the context. This allows |
| 300 |
defaults to be loaded from a configuration file to override the regular |
| 301 |
defaults. |
| 302 |
|
| 303 |
This is useful if you plug in some commands from another package but |
| 304 |
you're not satisfied with the defaults. |
| 305 |
|
| 306 |
The default map can be nested arbitrarily for each subcommand: |
| 307 |
|
| 308 |
```python |
| 309 |
|
| 310 |
default_map = { |
| 311 |
"debug": True, # default for a top level option |
| 312 |
"runserver": {"port": 5000} # default for a subcommand |
| 313 |
} |
| 314 |
``` |
| 315 |
|
| 316 |
The default map can be provided when the script is invoked, or |
| 317 |
overridden at any point by commands. For instance, a top-level command |
| 318 |
could load the defaults from a configuration file. |
| 319 |
|
| 320 |
Example usage: |
| 321 |
|
| 322 |
```{eval-rst} |
| 323 |
.. click:example:: |
| 324 |
|
| 325 |
import click |
| 326 |
|
| 327 |
@click.group() |
| 328 |
def cli(): |
| 329 |
pass |
| 330 |
|
| 331 |
@cli.command() |
| 332 |
@click.option('--port', default=8000) |
| 333 |
def runserver(port): |
| 334 |
click.echo(f"Serving on http://127.0.0.1:{port}/") |
| 335 |
|
| 336 |
if __name__ == '__main__': |
| 337 |
cli(default_map={ |
| 338 |
'runserver': { |
| 339 |
'port': 5000 |
| 340 |
} |
| 341 |
}) |
| 342 |
|
| 343 |
And in action: |
| 344 |
|
| 345 |
.. click:run:: |
| 346 |
|
| 347 |
invoke(cli, prog_name='cli', args=['runserver'], default_map={ |
| 348 |
'runserver': { |
| 349 |
'port': 5000 |
| 350 |
} |
| 351 |
}) |
| 352 |
``` |
| 353 |
|
| 354 |
## Context Defaults |
| 355 |
|
| 356 |
```{versionadded} 2.0 |
| 357 |
``` |
| 358 |
|
| 359 |
Starting with Click 2.0 you can override defaults for contexts not just |
| 360 |
when calling your script, but also in the decorator that declares a |
| 361 |
command. For instance given the previous example which defines a custom |
| 362 |
`default_map` this can also be accomplished in the decorator now. |
| 363 |
|
| 364 |
This example does the same as the previous example: |
| 365 |
|
| 366 |
```{eval-rst} |
| 367 |
.. click:example:: |
| 368 |
|
| 369 |
import click |
| 370 |
|
| 371 |
CONTEXT_SETTINGS = dict( |
| 372 |
default_map={'runserver': {'port': 5000}} |
| 373 |
) |
| 374 |
|
| 375 |
@click.group(context_settings=CONTEXT_SETTINGS) |
| 376 |
def cli(): |
| 377 |
pass |
| 378 |
|
| 379 |
@cli.command() |
| 380 |
@click.option('--port', default=8000) |
| 381 |
def runserver(port): |
| 382 |
click.echo(f"Serving on http://127.0.0.1:{port}/") |
| 383 |
|
| 384 |
if __name__ == '__main__': |
| 385 |
cli() |
| 386 |
|
| 387 |
And again the example in action: |
| 388 |
|
| 389 |
.. click:run:: |
| 390 |
|
| 391 |
invoke(cli, prog_name='cli', args=['runserver']) |
| 392 |
``` |
| 393 |
|
| 394 |
## Command Return Values |
| 395 |
|
| 396 |
```{versionadded} 3.0 |
| 397 |
``` |
| 398 |
|
| 399 |
One of the new introductions in Click 3.0 is the full support for return |
| 400 |
values from command callbacks. This enables a whole range of features |
| 401 |
that were previously hard to implement. |
| 402 |
|
| 403 |
In essence any command callback can now return a value. This return value |
| 404 |
is bubbled to certain receivers. One usecase for this has already been |
| 405 |
show in the example of {ref}`command-chaining` where it has been |
| 406 |
demonstrated that chained groups can have callbacks that process |
| 407 |
all return values. |
| 408 |
|
| 409 |
When working with command return values in Click, this is what you need to |
| 410 |
know: |
| 411 |
|
| 412 |
- The return value of a command callback is generally returned from the |
| 413 |
{meth}`Command.invoke` method. The exception to this rule has to |
| 414 |
do with {class}`Group`s: |
| 415 |
|
| 416 |
- In a group the return value is generally the return value of the |
| 417 |
subcommand invoked. The only exception to this rule is that the |
| 418 |
return value is the return value of the group callback if it's |
| 419 |
invoked without arguments and `invoke_without_command` is enabled. |
| 420 |
- If a group is set up for chaining then the return value is a list |
| 421 |
of all subcommands' results. |
| 422 |
- Return values of groups can be processed through a |
| 423 |
{attr}`Group.result_callback`. This is invoked with the |
| 424 |
list of all return values in chain mode, or the single return |
| 425 |
value in case of non chained commands. |
| 426 |
|
| 427 |
- The return value is bubbled through from the {meth}`Context.invoke` |
| 428 |
and {meth}`Context.forward` methods. This is useful in situations |
| 429 |
where you internally want to call into another command. |
| 430 |
|
| 431 |
- Click does not have any hard requirements for the return values and |
| 432 |
does not use them itself. This allows return values to be used for |
| 433 |
custom decorators or workflows (like in the command chaining |
| 434 |
example). |
| 435 |
|
| 436 |
- When a Click script is invoked as command line application (through |
| 437 |
{meth}`Command.main`) the return value is ignored unless the |
| 438 |
`standalone_mode` is disabled in which case it's bubbled through. |