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 Jaron Rosenau · committed by Jaron Rosenau · parent 014e24a · Browse files · 1 file+138 added−129 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+138 added−129 removed

  • other:+138 added−129 removed

1 file+138 added−129 removed

modified:docs/commands.md+138 added-129 removed
1Advanced Groups and Context2=============================1# Advanced Groups and Context24.. currentmodule:: click3```{currentmodule} click4```56In addition to the capabilities covered in the previous section, Groups have more advanced capabilities that leverage the Context.78.. contents::9 :depth: 110 :local:8```{contents}9---10depth: 111local: true12---13```1412Callback Invocation13-------------------15## Callback Invocation1617For a regular command, the callback is executed whenever the command runs.18If the script is the only command, it will always fire (unless a parameter19callback prevents it. This for instance happens if someone passes18``--help`` to the script).20`--help` to the script).2122For groups, the situation looks different. In this case, the callback fires23whenever a subcommand fires. What this means in practice is that an outer24command runs when an inner command runs:2526```{eval-rst}27.. click:example::2829 @click.group()30 @click.option('--debug/--no-debug', default=False)
10 unmodified lines
4142 invoke(cli, prog_name='tool.py')43 println()44 invoke(cli, prog_name='tool.py', args=['--debug', 'sync'])45```4643Nested Handling and Contexts44----------------------------47## Nested Handling and Contexts4849As you can see from the earlier example, the basic command group accepts a50debug argument which is passed to its callback, but not to the sync51command itself. The sync command only accepts its own arguments.5253This allows tools to act completely independent of each other, but how54does one command talk to a nested one? The answer to this is the52:class:`Context`.55{class}`Context`.5657Each time a command is invoked, a new context is created and linked with the58parent context. Normally, you can't see these contexts, but they are59there. Contexts are passed to parameter callbacks together with the60value automatically. Commands can also ask for the context to be passed58by marking themselves with the :func:`pass_context` decorator. In that61by marking themselves with the {func}`pass_context` decorator. In that62case, the context is passed as first argument.6364The context can also carry a program specified object that can be65used for the program's purposes. What this means is that you can build a66script like this:6768```{eval-rst}69.. click:example::7071 @click.group()72 @click.option('--debug/--no-debug', default=False)
11 unmodified lines
84 click.echo(f"Debug is {'on' if ctx.obj['DEBUG'] else 'off'}")8586 if __name__ == '__main__':87 cli(obj={})88```8990If the object is provided, each context will pass the object onwards to91its children, but at any level a context's object can be overridden. To87reach to a parent, ``context.parent`` can be used.92reach to a parent, `context.parent` can be used.9394In addition to that, instead of passing an object down, nothing stops the95application from modifying global state. For instance, you could just flip91a global ``DEBUG`` variable and be done with it.96a global `DEBUG` variable and be done with it.9793Decorating Commands94-------------------98## Decorating Commands99100As you have seen in the earlier example, a decorator can change how a101command is invoked. What actually happens behind the scenes is that98callbacks are always invoked through the :meth:`Context.invoke` method102callbacks are always invoked through the {meth}`Context.invoke` method103which automatically invokes a command correctly (by either passing the104context or not).105106This is very useful when you want to write custom decorators. For
1 unmodified line
108state and then storing it on the context and then to use a custom109decorator to find the most recent object of this sort and pass it as first110argument.111108For instance, the :func:`pass_obj` decorator can be implemented like this:112For instance, the {func}`pass_obj` decorator can be implemented like this:113114```{eval-rst}115.. click:example::116117 from functools import update_wrapper118
1 unmodified line
120 @click.pass_context121 def new_func(ctx, *args, **kwargs):122 return ctx.invoke(f, ctx.obj, *args, **kwargs)123 return update_wrapper(new_func, f)124```125120The :meth:`Context.invoke` command will automatically invoke the function121in the correct way, so the function will either be called with ``f(ctx,122obj)`` or ``f(obj)`` depending on whether or not it itself is decorated with123:func:`pass_context`.126The {meth}`Context.invoke` command will automatically invoke the function127in the correct way, so the function will either be called with`f(ctx,128obj)` or `f(obj)` depending on whether or not it itself is decorated with129{func}`pass_context`.130131This is a very powerful concept that can be used to build very complex126nested applications; see :ref:`complex-guide` for more information.132nested applications; see {ref}`complex-guide` for more information.133128.. _command-chaining:134(command-chaining)=135130Command Chaining131----------------136## Command Chaining137138It is useful to invoke more than one subcommand in one call. For example,134``my-app validate build upload`` would invoke ``validate``, then ``build``, then135``upload``. To implement this, pass ``chain=True`` when creating a group.139`my-app validate build upload` would invoke `validate`, then `build`, then140`upload`. To implement this, pass `chain=True` when creating a group.141142```{eval-rst}143.. click:example::144145 @click.group(chain=True)146 def cli():
11 unmodified lines
158159.. click:run::160161 invoke(cli, prog_name='my-app', args=['validate', 'build'])162```163164When using chaining, there are a few restrictions:165159- Only the last command may use ``nargs=-1`` on an argument, otherwise the160 parser will not be able to find further commands.161- It is not possible to nest groups below a chain group.162- On the command line, options must be specified before arguments for each163 command in the chain.164- The :attr:`Context.invoked_subcommand` attribute will be ``'*'`` because the165 parser doesn't know the full list of commands that will run yet.166- Only the last command may use `nargs=-1` on an argument, otherwise the167 parser will not be able to find further commands.168- It is not possible to nest groups below a chain group.169- On the command line, options must be specified before arguments for each170 command in the chain.171- The {attr}`Context.invoked_subcommand` attribute will be `'*'` because the172 parser doesn't know the full list of commands that will run yet.173167.. _command-pipelines:174(command-pipelines)=175169Command Pipelines170------------------176## Command Pipelines177178When using chaining, a common pattern is to have each command process the179result of the previous command.180175A straightforward way to do this is to use :func:`make_pass_decorator` to pass181A straightforward way to do this is to use {func}`make_pass_decorator` to pass182a context object to each command, and store and read the data on that object.183184```{eval-rst}185.. click:example::186187 pass_ns = click.make_pass_decorator(dict, ensure=True)188
15 unmodified lines
204205.. click:run::206207 invoke(cli, prog_name="process", args=["Click", "show", "lower", "show"])208```209210Another way to do this is to collect data returned by each command, then process203it at the end of the chain. Use the group's :meth:`~Group.result_callback`211it at the end of the chain. Use the group's {meth}`~Group.result_callback`212decorator to register a function that is called after the chain is finished. It213is passed the list of return values as well as any parameters registered on the214group.215
2 unmodified lines
218result callback calls each function. The command takes a file, processes each219line, then outputs it. If no subcommands are given, it outputs the contents220of the file unchanged.221214.. code-block:: python222```python223@click.group(chain=True, invoke_without_command=True)224@click.argument("fin", type=click.File("r"))225def cli(fin):226 pass227216 @click.group(chain=True, invoke_without_command=True)217 @click.argument("fin", type=click.File("r"))218 def cli(fin):219 pass228@cli.result_callback()229def process_pipeline(processors, fin):230 iterator = (x.rstrip("\r\n") for x in input)231221 @cli.result_callback()222 def process_pipeline(processors, fin):223 iterator = (x.rstrip("\r\n") for x in input)232 for processor in processors:233 iterator = processor(iterator)234225 for processor in processors:226 iterator = processor(iterator)235 for item in iterator:236 click.echo(item)237228 for item in iterator:229 click.echo(item)238@cli.command("upper")239def make_uppercase():240 def processor(iterator):241 for line in iterator:242 yield line.upper()243 return processor244231 @cli.command("upper")232 def make_uppercase():233 def processor(iterator):234 for line in iterator:235 yield line.upper()236 return processor245@cli.command("lower")246def make_lowercase():247 def processor(iterator):248 for line in iterator:249 yield line.lower()250 return processor251238 @cli.command("lower")239 def make_lowercase():240 def processor(iterator):241 for line in iterator:242 yield line.lower()243 return processor252@cli.command("strip")253def make_strip():254 def processor(iterator):255 for line in iterator:256 yield line.strip()257 return processor258```259245 @cli.command("strip")246 def make_strip():247 def processor(iterator):248 for line in iterator:249 yield line.strip()250 return processor251260That's a lot in one go, so let's go through it step by step.2612541. The first thing is to make a :func:`group` that is chainable. In255 addition to that we also instruct Click to invoke even if no256 subcommand is defined. If this would not be done, then invoking an257 empty pipeline would produce the help page instead of running the258 result callbacks.2592. The next thing we do is to register a result callback on our group.260 This callback will be invoked with an argument which is the list of261 all return values of all subcommands and then the same keyword262 parameters as our group itself. This means we can access the input263 file easily there without having to use the context object.2643. In this result callback we create an iterator of all the lines in the265 input file and then pass this iterator through all the returned266 callbacks from all subcommands and finally we print all lines to267 stdout.2621. The first thing is to make a {func}`group` that is chainable. In263 addition to that we also instruct Click to invoke even if no264 subcommand is defined. If this would not be done, then invoking an265 empty pipeline would produce the help page instead of running the266 result callbacks.2672. The next thing we do is to register a result callback on our group.268 This callback will be invoked with an argument which is the list of269 all return values of all subcommands and then the same keyword270 parameters as our group itself. This means we can access the input271 file easily there without having to use the context object.2723. In this result callback we create an iterator of all the lines in the273 input file and then pass this iterator through all the returned274 callbacks from all subcommands and finally we print all lines to275 stdout.276277After that point we can register as many subcommands as we want and each278subcommand can return a processor function to modify the stream of lines.279
2 unmodified lines
282cannot be accessed in the `processor` functions as the files will already283be closed there. This limitation is unlikely to change because it would284make resource handling much more complicated. For such it's recommended285to not use the file type and manually open the file through278:func:`open_file`.286{func}`open_file`.287288For a more complex example that also improves upon handling of the pipelines,281see the `imagepipe example`_ in the Click repository. It implements a282pipeline based image editing tool that has a nice internal structure.289see the [imagepipe example](https://github.com/pallets/click/tree/main/examples/imagepipe)290in the Click repository. It implements a pipeline based image editing tool291that has a nice internal structure.292284.. _imagepipe example: https://github.com/pallets/click/tree/main/examples/imagepipe293## Overriding Defaults294286287Overriding Defaults288-------------------289295By default, the default value for a parameter is pulled from the291``default`` flag that is provided when it's defined, but that's not the296`default` flag that is provided when it's defined, but that's not the297only place defaults can be loaded from. The other place is the293:attr:`Context.default_map` (a dictionary) on the context. This allows298{attr}`Context.default_map` (a dictionary) on the context. This allows299defaults to be loaded from a configuration file to override the regular300defaults.301302This is useful if you plug in some commands from another package but303you're not satisfied with the defaults.304305The default map can be nested arbitrarily for each subcommand:306302.. code-block:: python307```python308309 default_map = {310 "debug": True, # default for a top level option311 "runserver": {"port": 5000} # default for a subcommand312 }313```314315The default map can be provided when the script is invoked, or316overridden at any point by commands. For instance, a top-level command317could load the defaults from a configuration file.318319Example usage:320321```{eval-rst}322.. click:example::323324 import click325
21 unmodified lines
347 'runserver': {348 'port': 5000349 }350 })351```352345Context Defaults346----------------353## Context Defaults354348.. versionadded:: 2.0355```{versionadded} 2.0356```357358Starting with Click 2.0 you can override defaults for contexts not just359when calling your script, but also in the decorator that declares a360command. For instance given the previous example which defines a custom353``default_map`` this can also be accomplished in the decorator now.361`default_map` this can also be accomplished in the decorator now.362363This example does the same as the previous example:364365```{eval-rst}366.. click:example::367368 import click369
17 unmodified lines
387388.. click:run::389390 invoke(cli, prog_name='cli', args=['runserver'])391```392393## Command Return Values394384Command Return Values385---------------------395```{versionadded} 3.0396```397387.. versionadded:: 3.0388398One of the new introductions in Click 3.0 is the full support for return399values from command callbacks. This enables a whole range of features400that were previously hard to implement.401402In essence any command callback can now return a value. This return value403is bubbled to certain receivers. One usecase for this has already been395show in the example of :ref:`command-chaining` where it has been404show in the example of {ref}`command-chaining` where it has been405demonstrated that chained groups can have callbacks that process406all return values.407408When working with command return values in Click, this is what you need to409know:410402- The return value of a command callback is generally returned from the403 :meth:`Command.invoke` method. The exception to this rule has to404 do with :class:`Group`\s:411- The return value of a command callback is generally returned from the412 {meth}`Command.invoke` method. The exception to this rule has to413 do with {class}`Group`s:414406 * In a group the return value is generally the return value of the407 subcommand invoked. The only exception to this rule is that the408 return value is the return value of the group callback if it's409 invoked without arguments and `invoke_without_command` is enabled.410 * If a group is set up for chaining then the return value is a list411 of all subcommands' results.412 * Return values of groups can be processed through a413 :attr:`Group.result_callback`. This is invoked with the414 list of all return values in chain mode, or the single return415 value in case of non chained commands.415 - In a group the return value is generally the return value of the416 subcommand invoked. The only exception to this rule is that the417 return value is the return value of the group callback if it's418 invoked without arguments and `invoke_without_command` is enabled.419 - If a group is set up for chaining then the return value is a list420 of all subcommands' results.421 - Return values of groups can be processed through a422 {attr}`Group.result_callback`. This is invoked with the423 list of all return values in chain mode, or the single return424 value in case of non chained commands.425417- The return value is bubbled through from the :meth:`Context.invoke`418 and :meth:`Context.forward` methods. This is useful in situations419 where you internally want to call into another command.426- The return value is bubbled through from the {meth}`Context.invoke`427 and {meth}`Context.forward` methods. This is useful in situations428 where you internally want to call into another command.429421- Click does not have any hard requirements for the return values and422 does not use them itself. This allows return values to be used for423 custom decorators or workflows (like in the command chaining424 example).430- Click does not have any hard requirements for the return values and431 does not use them itself. This allows return values to be used for432 custom decorators or workflows (like in the command chaining433 example).434426- When a Click script is invoked as command line application (through427 :meth:`Command.main`) the return value is ignored unless the428 `standalone_mode` is disabled in which case it's bubbled through.435- When a Click script is invoked as command line application (through436 {meth}`Command.main`) the return value is ignored unless the437 `standalone_mode` is disabled in which case it's bubbled through.