Skip to content
Myr

advanced.md

This file

Path

docs/advanced.md

421 lines · 13.8 KiB · Markdown

Last changed by

Merge stable into main (#3521)Rowlando13before adoption1a994ad

History of this file

Take it

Show it rendered

1# Advanced Patterns23```{currentmodule} click4```56In addition to common functionality, Click offers some advanced features.78```{contents}9:depth: 110:local: true11```1213## Callbacks and Eager Options1415Sometimes, you want a parameter to completely change the execution flow.16For instance, this is the case when you want to have a `--version`17parameter that prints out the version and then exits the application.1819Note: an actual implementation of a `--version` parameter that is20reusable is available in Click as {func}`click.version_option`. The code21here is merely an example of how to implement such a flag.2223In such cases, you need two concepts: eager parameters and a callback. An24eager parameter is a parameter handled before others, and a25callback is what executes after the parameter is handled. The eagerness26is necessary so that an earlier required parameter does not produce an27error message. For instance, if `--version` was not eager and a28parameter `--foo` was required and defined before, you would need to29specify it for `--version` to work. For more information, see30{ref}`callback-evaluation-order`.3132A callback is a function invoked with three parameters: the33current {class}`Context`, the current {class}`Parameter`, and the value.34The context provides some useful features such as quitting the35application and gives access to other already processed parameters.3637Here's an example for a `--version` flag:3839```{eval-rst}40.. click:example::4142    def print_version(ctx, param, value):43        if not value or ctx.resilient_parsing:44            return45        click.echo('Version 1.0')46        ctx.exit()4748    @click.command()49    @click.option('--version', is_flag=True, callback=print_version,50                  expose_value=False, is_eager=True)51    def hello():52        click.echo('Hello World!')535455What it looks like:565758.. click:run::5960    invoke(hello)61    invoke(hello, args=['--version'])62```63The `expose_value` parameter prevents the pretty pointless `version`64parameter from being passed to the callback. If that was not specified, a65boolean would be passed to the `hello` script. The `resilient_parsing`66flag is applied to the context if Click wants to parse the command line67without any destructive behavior that would change the execution flow. In68this case, because we would exit the program, we instead do nothing.6970## Callbacks for Validation7172```{versionchanged} 2.073```7475If you want to apply custom validation logic, you can do this in the76parameter callbacks. These callbacks can both modify values and77raise errors if the validation does not work. The callback runs after78type conversion. It is called for all sources, including prompts.7980In Click 1.0, you can only raise the {exc}`UsageError` but starting with81Click 2.0, you can also raise the {exc}`BadParameter` error, which has the82added advantage that it will automatically format the error message to83also contain the parameter name.8485```{eval-rst}86.. click:example::8788    def validate_rolls(ctx, param, value):89        if isinstance(value, tuple):90            return value9192        try:93            rolls, _, dice = value.partition("d")94            return int(dice), int(rolls)95        except ValueError:96            raise click.BadParameter("format must be 'NdM'")9798    @click.command()99    @click.option(100        "--rolls", type=click.UNPROCESSED, callback=validate_rolls,101        default="1d6", prompt=True,102    )103    def roll(rolls):104        sides, times = rolls105        click.echo(f"Rolling a {sides}-sided dice {times} time(s)")106107.. click:run::108109    invoke(roll, args=["--rolls=42"])110    println()111    invoke(roll, args=["--rolls=2d12"])112    println()113    invoke(roll, input=["42", "2d12"])114```115116## Parameter Modifications117118Parameters (options and arguments) are forwarded to the command callbacks,119as you have seen. One common way to prevent a parameter from being passed120to the callback is the `expose_value` argument to a parameter which hides121the parameter entirely. The way this works is that the {class}`Context`122object has a {attr}`~Context.params` attribute which is a dictionary of123all parameters. Whatever is in that dictionary is being passed to the124callbacks.125126This can be used to make up additional parameters. Generally, this pattern127is not recommended, but in some cases it can be useful. At the very least,128it's good to know that the system works this way.129130```{eval-rst}131.. click:example::132133    import urllib.request134135    def open_url(ctx, param, value):136        if value is not None:137            ctx.params['fp'] = urllib.request.urlopen(value)138            return value139140    @click.command()141    @click.option('--url', callback=open_url)142    def cli(url, fp=None):143        if fp is not None:144            click.echo(f"{url}: {fp.code}")145146In this case the callback returns the URL unchanged but also passes a147second `fp` value to the callback.148149.. caution::150151   Writing to :attr:`~click.Context.params` directly bypasses Click's152   per-parameter pipeline: :meth:`~click.Context.get_parameter_source` returns153   ``None`` for it, the value is never run through any :class:`~click.ParamType`154   conversion. And if the key collides with a declared parameter, then the155   shared-name arbitration loses information about where the value came from.156   Prefer the wrapper pattern below when any of those semantics matter.157158What's more recommended is to pass the information in a wrapper, however:159160.. click:example::161162    import urllib.request163164    class URL:165        def __init__(self, url, fp):166            self.url = url167            self.fp = fp168169    def open_url(ctx, param, value):170        if value is not None:171            return URL(value, urllib.request.urlopen(value))172173    @click.command()174    @click.option('--url', callback=open_url)175    def cli(url):176        if url is not None:177            click.echo(f"{url.url}: {url.fp.code}")178179```180181## Token Normalization182183```{versionadded} 2.0184```185186Starting with Click 2.0, it's possible to provide a function used187for normalizing tokens. Tokens are option names, choice values, or command188values. This can be used to implement case-insensitive options, for189instance.190191To use this feature, the context needs to be passed a function that192performs the normalization of the token. Such as a function that converts the193token to lowercase:194195```{eval-rst}196.. click:example::197198    CONTEXT_SETTINGS = {'token_normalize_func': lambda x: x.lower()}199200    @click.command(context_settings=CONTEXT_SETTINGS)201    @click.option('--name', default='Pete')202    def cli(name):203        click.echo(f"Name: {name}")204205# And how it works on the command line:206207.. click:run::208209    invoke(cli, prog_name='cli', args=['--NAME=Pete'])210```211212## Invoking Other Commands213214Sometimes, it might be interesting to invoke one command from another215command. This is a pattern generally discouraged with Click, but216possible nonetheless. For this, you can use the {func}`Context.invoke`217or {func}`Context.forward` methods.218219They work similarly, but the difference is that {func}`Context.invoke` merely220invokes another command with the arguments you provide as a caller,221whereas {func}`Context.forward` fills in the arguments from the current222command. Both accept the command as the first argument, and everything else223is passed onwards as you would expect.224225Example:226227```{eval-rst}228.. click:example::229230    cli = click.Group()231232    @cli.command()233    @click.option('--count', default=1)234    def test(count):235        click.echo(f'Count: {count}')236237    @cli.command()238    @click.option('--count', default=1)239    @click.pass_context240    def dist(ctx, count):241        ctx.forward(test)242        ctx.invoke(test, count=42)243244And what it looks like:245246.. click:run::247248    invoke(cli, prog_name='cli', args=['dist'])249```250251(forwarding-unknown-options)=252253## Forwarding Unknown Options254255In some situations, it is interesting to be able to accept all unknown256options for further manual processing. Click can generally do that as of257Click 4.0, but it has some limitations that lie in the nature of the258problem. The support for this is provided through a parser flag called259`ignore_unknown_options` which will instruct the parser to collect all260unknown options and to put them to the leftover argument instead of261triggering a parsing error.262263This can generally be activated in two different ways:2642651. It can be enabled on custom {class}`Command` subclasses by changing266   the {attr}`~Command.ignore_unknown_options` attribute.2672. It can be enabled by changing the attribute of the same name on the268   context class ({attr}`Context.ignore_unknown_options`). This is best269   changed through the `context_settings` dictionary on the command.270271For most situations, the easiest solution is the second. Once the behavior272is changed, something needs to pick up those leftover options (which at273this point are considered arguments). For this again, you have two274options:2752761. You can use {func}`pass_context` to get the context passed. This will277   only work if in addition to {attr}`~Context.ignore_unknown_options`278   you also set {attr}`~Context.allow_extra_args` as otherwise the279   command will abort with an error that there are leftover arguments.280   If you go with this solution, the extra arguments will be collected in281   {attr}`Context.args`.2822. You can attach an {func}`argument` with `nargs` set to `-1` which283   will eat up all leftover arguments. In this case it's recommended to284   set the `type` to {data}`UNPROCESSED` to avoid any string processing285   on those arguments as otherwise they are forced into Unicode strings286   automatically which is often not what you want.287288In the end, the result looks something like this:289290```{eval-rst}291.. click:example::292293    from subprocess import call294295    @click.command(context_settings={'ignore_unknown_options': True})296    @click.option('-v', '--verbose', is_flag=True, help='Enables verbose mode')297    @click.argument('timeit_args', nargs=-1, type=click.UNPROCESSED)298    def cli(verbose, timeit_args):299        """A fake wrapper around Python's timeit."""300        cmdline = ['echo', 'python', '-mtimeit', *timeit_args]301        if verbose:302            click.echo(f"Invoking: {' '.join(cmdline)}")303        call(cmdline)304305306And the final output resembles the following:307308.. click:run::309310    invoke(cli, prog_name='cli', args=['--help'])311    println()312    invoke(cli, prog_name='cli', args=['-n', '100', 'a = 1; b = 2; a * b'])313    println()314    invoke(cli, prog_name='cli', args=['-v', 'a = 1; b = 2; a * b'])315```316317As you can see, Click handles the verbosity flag and everything else318ends up in the `timeit_args` variable for further processing, which then319for instance, allows invoking a subprocess. There are a few things that320are important to know about how this ignoring of unhandled flag happens:321322- Unknown long options are generally ignored and not processed at all.323  So for instance if `--foo=bar` or `--foo bar` are passed they324  generally end up like that. Note that because the parser cannot know325  if an option will accept an argument or not, the `bar` part might be326  handled as an argument.327- Unknown short options might be partially handled and reassembled if328  necessary. For instance in the above example there is an option329  called `-v` which enables verbose mode. If the command would be330  invoked with `-va` then the `-v` part would be handled by Click331  (as it is known) and `-a` would end up in the leftover parameters332  for further processing.333- Depending on what you plan on doing you might have some success by334  disabling interspersed arguments335  ({attr}`~Context.allow_interspersed_args`) which instructs the parser336  to not allow arguments and options to be mixed. Depending on your337   situation, this might improve your results.338339Generally, combining the handling of options and arguments from your own340commands with those from another application is discouraged, and you341should avoid it if possible. It's a much better idea to have342everything below a subcommand be forwarded to another application than to343handle some arguments yourself.344345## Managing Resources346347It can be useful to open a resource in a group, to be made available to348subcommands. Many types of resources need to be closed or otherwise349cleaned up after use. The standard way to do this in Python is by using350a context manager with the `with` statement.351352For example, the `Repo` class from {doc}`complex` might actually be353defined as a context manager:354355```python356class Repo:357    def __init__(self, home=None):358        self.home = os.path.abspath(home or ".")359        self.db = None360361    def __enter__(self):362        path = os.path.join(self.home, "repo.db")363        self.db = open_database(path)364        return self365366    def __exit__(self, exc_type, exc_value, tb):367        self.db.close()368```369370Ordinarily, it would be used with the `with` statement:371372```python373with Repo() as repo:374    repo.db.query(...)375```376377However, a `with` block in a group would exit and close the database378before it could be used by a subcommand.379380Instead, use the context's {meth}`~click.Context.with_resource` method381to enter the context manager and return the resource. When the group and382any subcommands finish, the context's resources are cleaned up.383384```python385@click.group()386@click.option("--repo-home", default=".repo")387@click.pass_context388def cli(ctx, repo_home):389    ctx.obj = ctx.with_resource(Repo(repo_home))390391@cli.command()392@click.pass_obj393def log(obj):394    # obj is the repo opened in the cli group395    for entry in obj.db.query(...):396        click.echo(entry)397```398399If the resource isn't a context manager, usually it can be wrapped in400one using something from {mod}`contextlib`. If that's not possible, use401the context's {meth}`~click.Context.call_on_close` method to register a402cleanup function.403404```python405@click.group()406@click.option("--name", default="repo.db")407@click.pass_context408def cli(ctx, name):409    ctx.obj = db = open_db(name)410411    @ctx.call_on_close412    def close_db():413        db.record_use()414        db.save()415        db.close()416```417418```{versionchanged} 8.2419`Context.call_on_close` and context managers registered via `Context.with_resource`420will be closed when the CLI exits. These were previously not called on exit.421```