advanced.md
This file
Path
docs/advanced.md
425 lines · 13.9 KiB · Markdown
Last changed by
Fix `get_parameter_source()` during type conversion and eager callbacks (#3484)David Lordbefore adoptiond42f15b
History of this fileTake it
Convert advanced.rst to MyST (#3061)Rowlando13before adoptionf6a87df
lines 1–146why, one step back1# 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 urllib134135 def open_url(ctx, param, value):136 if value is not None:137 ctx.params['fp'] = urllib.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 aFix `get_parameter_source()` during type conversion and eager callbacks (#3484)David Lordbefore adoptiond42f15b
lines 147–158why, one step back147second `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:Convert advanced.rst to MyST (#3061)Rowlando13before adoptionf6a87df
lines 159–425why, one step back159160.. click:example::161162 import urllib163164 class URL(object):165166 def __init__(self, url, fp):167 self.url = url168 self.fp = fp169170 def open_url(ctx, param, value):171 if value is not None:172 return URL(value, urllib.urlopen(value))173174 @click.command()175 @click.option('--url', callback=open_url)176 def cli(url):177 if url is not None:178 click.echo(f"{url.url}: {url.fp.code}")179180```181182## Token Normalization183184```{versionadded} 2.0185```186187Starting with Click 2.0, it's possible to provide a function used188for normalizing tokens. Tokens are option names, choice values, or command189values. This can be used to implement case-insensitive options, for190instance.191192To use this feature, the context needs to be passed a function that193performs the normalization of the token. Such as a function that converts the194token to lowercase:195196```{eval-rst}197.. click:example::198199 CONTEXT_SETTINGS = dict(token_normalize_func=lambda x: x.lower())200201 @click.command(context_settings=CONTEXT_SETTINGS)202 @click.option('--name', default='Pete')203 def cli(name):204 click.echo(f"Name: {name}")205206# And how it works on the command line:207208.. click:run::209210 invoke(cli, prog_name='cli', args=['--NAME=Pete'])211```212213## Invoking Other Commands214215Sometimes, it might be interesting to invoke one command from another216command. This is a pattern generally discouraged with Click, but217possible nonetheless. For this, you can use the {func}`Context.invoke`218or {func}`Context.forward` methods.219220They work similarly, but the difference is that {func}`Context.invoke` merely221invokes another command with the arguments you provide as a caller,222whereas {func}`Context.forward` fills in the arguments from the current223command. Both accept the command as the first argument, and everything else224is passed onwards as you would expect.225226Example:227228```{eval-rst}229.. click:example::230231 cli = click.Group()232233 @cli.command()234 @click.option('--count', default=1)235 def test(count):236 click.echo(f'Count: {count}')237238 @cli.command()239 @click.option('--count', default=1)240 @click.pass_context241 def dist(ctx, count):242 ctx.forward(test)243 ctx.invoke(test, count=42)244245And what it looks like:246247.. click:run::248249 invoke(cli, prog_name='cli', args=['dist'])250```251252(forwarding-unknown-options)=253254## Forwarding Unknown Options255256In some situations, it is interesting to be able to accept all unknown257options for further manual processing. Click can generally do that as of258Click 4.0, but it has some limitations that lie in the nature of the259problem. The support for this is provided through a parser flag called260`ignore_unknown_options` which will instruct the parser to collect all261unknown options and to put them to the leftover argument instead of262triggering a parsing error.263264This can generally be activated in two different ways:2652661. It can be enabled on custom {class}`Command` subclasses by changing267 the {attr}`~Command.ignore_unknown_options` attribute.2682. It can be enabled by changing the attribute of the same name on the269 context class ({attr}`Context.ignore_unknown_options`). This is best270 changed through the `context_settings` dictionary on the command.271272For most situations, the easiest solution is the second. Once the behavior273is changed, something needs to pick up those leftover options (which at274this point are considered arguments). For this again, you have two275options:2762771. You can use {func}`pass_context` to get the context passed. This will278 only work if in addition to {attr}`~Context.ignore_unknown_options`279 you also set {attr}`~Context.allow_extra_args` as otherwise the280 command will abort with an error that there are leftover arguments.281 If you go with this solution, the extra arguments will be collected in282 {attr}`Context.args`.2832. You can attach an {func}`argument` with `nargs` set to `-1` which284 will eat up all leftover arguments. In this case it's recommended to285 set the `type` to {data}`UNPROCESSED` to avoid any string processing286 on those arguments as otherwise they are forced into Unicode strings287 automatically which is often not what you want.288289In the end, the result looks something like this:290291```{eval-rst}292.. click:example::293294 import sys295 from subprocess import call296297 @click.command(context_settings=dict(298 ignore_unknown_options=True,299 ))300 @click.option('-v', '--verbose', is_flag=True, help='Enables verbose mode')301 @click.argument('timeit_args', nargs=-1, type=click.UNPROCESSED)302 def cli(verbose, timeit_args):303 """A fake wrapper around Python's timeit."""304 cmdline = ['echo', 'python', '-mtimeit'] + list(timeit_args)305 if verbose:306 click.echo(f"Invoking: {' '.join(cmdline)}")307 call(cmdline)308309310And the final output resembles the following:311312.. click:run::313314 invoke(cli, prog_name='cli', args=['--help'])315 println()316 invoke(cli, prog_name='cli', args=['-n', '100', 'a = 1; b = 2; a * b'])317 println()318 invoke(cli, prog_name='cli', args=['-v', 'a = 1; b = 2; a * b'])319```320321As you can see, Click handles the verbosity flag and everything else322ends up in the `timeit_args` variable for further processing, which then323for instance, allows invoking a subprocess. There are a few things that324are important to know about how this ignoring of unhandled flag happens:325326- Unknown long options are generally ignored and not processed at all.327 So for instance if `--foo=bar` or `--foo bar` are passed they328 generally end up like that. Note that because the parser cannot know329 if an option will accept an argument or not, the `bar` part might be330 handled as an argument.331- Unknown short options might be partially handled and reassembled if332 necessary. For instance in the above example there is an option333 called `-v` which enables verbose mode. If the command would be334 ignored with `-va` then the `-v` part would be handled by Click335 (as it is known) and `-a` would end up in the leftover parameters336 for further processing.337- Depending on what you plan on doing you might have some success by338 disabling interspersed arguments339 ({attr}`~Context.allow_interspersed_args`) which instructs the parser340 to not allow arguments and options to be mixed. Depending on your341 situation, this might improve your results.342343Generally, combining the handling of options and arguments from your own344commands with those from another application is discouraged, and you345should avoid it if possible. It's a much better idea to have346everything below a subcommand be forwarded to another application than to347handle some arguments yourself.348349## Managing Resources350351It can be useful to open a resource in a group, to be made available to352subcommands. Many types of resources need to be closed or otherwise353cleaned up after use. The standard way to do this in Python is by using354a context manager with the `with` statement.355356For example, the `Repo` class from {doc}`complex` might actually be357defined as a context manager:358359```python360class Repo:361 def __init__(self, home=None):362 self.home = os.path.abspath(home or ".")363 self.db = None364365 def __enter__(self):366 path = os.path.join(self.home, "repo.db")367 self.db = open_database(path)368 return self369370 def __exit__(self, exc_type, exc_value, tb):371 self.db.close()372```373374Ordinarily, it would be used with the `with` statement:375376```python377with Repo() as repo:378 repo.db.query(...)379```380381However, a `with` block in a group would exit and close the database382before it could be used by a subcommand.383384Instead, use the context's {meth}`~click.Context.with_resource` method385to enter the context manager and return the resource. When the group and386any subcommands finish, the context's resources are cleaned up.387388```python389@click.group()390@click.option("--repo-home", default=".repo")391@click.pass_context392def cli(ctx, repo_home):393 ctx.obj = ctx.with_resource(Repo(repo_home))394395@cli.command()396@click.pass_obj397def log(obj):398 # obj is the repo opened in the cli group399 for entry in obj.db.query(...):400 click.echo(entry)401```402403If the resource isn't a context manager, usually it can be wrapped in404one using something from {mod}`contextlib`. If that's not possible, use405the context's {meth}`~click.Context.call_on_close` method to register a406cleanup function.407408```python409@click.group()410@click.option("--name", default="repo.db")411@click.pass_context412def cli(ctx, repo_home):413 ctx.obj = db = open_db(repo_home)414415 @ctx.call_on_close416 def close_db():417 db.record_use()418 db.save()419 db.close()420```421422```{versionchanged} 8.2423`Context.call_on_close` and context managers registered via `Context.with_resource`424will be closed when the CLI exits. These were previously not called on exit.425```