Debian Codegraph @

docs/advanced.md

raw
1 # Advanced Patterns
2
3 ```{currentmodule} click
4 ```
5
6 In addition to common functionality, Click offers some advanced features.
7
8 ```{contents}
9 :depth: 1
10 :local: true
11 ```
12
13 ## Callbacks and Eager Options
14
15 Sometimes, you want a parameter to completely change the execution flow.
16 For instance, this is the case when you want to have a `--version`
17 parameter that prints out the version and then exits the application.
18
19 Note: an actual implementation of a `--version` parameter that is
20 reusable is available in Click as {func}`click.version_option`. The code
21 here is merely an example of how to implement such a flag.
22
23 In such cases, you need two concepts: eager parameters and a callback. An
24 eager parameter is a parameter handled before others, and a
25 callback is what executes after the parameter is handled. The eagerness
26 is necessary so that an earlier required parameter does not produce an
27 error message. For instance, if `--version` was not eager and a
28 parameter `--foo` was required and defined before, you would need to
29 specify it for `--version` to work. For more information, see
30 {ref}`callback-evaluation-order`.
31
32 A callback is a function invoked with three parameters: the
33 current {class}`Context`, the current {class}`Parameter`, and the value.
34 The context provides some useful features such as quitting the
35 application and gives access to other already processed parameters.
36
37 Here's an example for a `--version` flag:
38
39 ```{eval-rst}
40 .. click:example::
41
42 def print_version(ctx, param, value):
43 if not value or ctx.resilient_parsing:
44 return
45 click.echo('Version 1.0')
46 ctx.exit()
47
48 @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!')
53
54
55 What it looks like:
56
57
58 .. click:run::
59
60 invoke(hello)
61 invoke(hello, args=['--version'])
62 ```
63 The `expose_value` parameter prevents the pretty pointless `version`
64 parameter from being passed to the callback. If that was not specified, a
65 boolean would be passed to the `hello` script. The `resilient_parsing`
66 flag is applied to the context if Click wants to parse the command line
67 without any destructive behavior that would change the execution flow. In
68 this case, because we would exit the program, we instead do nothing.
69
70 ## Callbacks for Validation
71
72 ```{versionchanged} 2.0
73 ```
74
75 If you want to apply custom validation logic, you can do this in the
76 parameter callbacks. These callbacks can both modify values and
77 raise errors if the validation does not work. The callback runs after
78 type conversion. It is called for all sources, including prompts.
79
80 In Click 1.0, you can only raise the {exc}`UsageError` but starting with
81 Click 2.0, you can also raise the {exc}`BadParameter` error, which has the
82 added advantage that it will automatically format the error message to
83 also contain the parameter name.
84
85 ```{eval-rst}
86 .. click:example::
87
88 def validate_rolls(ctx, param, value):
89 if isinstance(value, tuple):
90 return value
91
92 try:
93 rolls, _, dice = value.partition("d")
94 return int(dice), int(rolls)
95 except ValueError:
96 raise click.BadParameter("format must be 'NdM'")
97
98 @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 = rolls
105 click.echo(f"Rolling a {sides}-sided dice {times} time(s)")
106
107 .. click:run::
108
109 invoke(roll, args=["--rolls=42"])
110 println()
111 invoke(roll, args=["--rolls=2d12"])
112 println()
113 invoke(roll, input=["42", "2d12"])
114 ```
115
116 ## Parameter Modifications
117
118 Parameters (options and arguments) are forwarded to the command callbacks,
119 as you have seen. One common way to prevent a parameter from being passed
120 to the callback is the `expose_value` argument to a parameter which hides
121 the parameter entirely. The way this works is that the {class}`Context`
122 object has a {attr}`~Context.params` attribute which is a dictionary of
123 all parameters. Whatever is in that dictionary is being passed to the
124 callbacks.
125
126 This can be used to make up additional parameters. Generally, this pattern
127 is not recommended, but in some cases it can be useful. At the very least,
128 it's good to know that the system works this way.
129
130 ```{eval-rst}
131 .. click:example::
132
133 import urllib
134
135 def open_url(ctx, param, value):
136 if value is not None:
137 ctx.params['fp'] = urllib.urlopen(value)
138 return value
139
140 @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}")
145
146 In this case the callback returns the URL unchanged but also passes a
147 second `fp` value to the callback. What's more recommended is to pass
148 the information in a wrapper, however:
149
150 .. click:example::
151
152 import urllib
153
154 class URL(object):
155
156 def __init__(self, url, fp):
157 self.url = url
158 self.fp = fp
159
160 def open_url(ctx, param, value):
161 if value is not None:
162 return URL(value, urllib.urlopen(value))
163
164 @click.command()
165 @click.option('--url', callback=open_url)
166 def cli(url):
167 if url is not None:
168 click.echo(f"{url.url}: {url.fp.code}")
169
170 ```
171
172 ## Token Normalization
173
174 ```{versionadded} 2.0
175 ```
176
177 Starting with Click 2.0, it's possible to provide a function used
178 for normalizing tokens. Tokens are option names, choice values, or command
179 values. This can be used to implement case-insensitive options, for
180 instance.
181
182 To use this feature, the context needs to be passed a function that
183 performs the normalization of the token. Such as a function that converts the
184 token to lowercase:
185
186 ```{eval-rst}
187 .. click:example::
188
189 CONTEXT_SETTINGS = dict(token_normalize_func=lambda x: x.lower())
190
191 @click.command(context_settings=CONTEXT_SETTINGS)
192 @click.option('--name', default='Pete')
193 def cli(name):
194 click.echo(f"Name: {name}")
195
196 # And how it works on the command line:
197
198 .. click:run::
199
200 invoke(cli, prog_name='cli', args=['--NAME=Pete'])
201 ```
202
203 ## Invoking Other Commands
204
205 Sometimes, it might be interesting to invoke one command from another
206 command. This is a pattern generally discouraged with Click, but
207 possible nonetheless. For this, you can use the {func}`Context.invoke`
208 or {func}`Context.forward` methods.
209
210 They work similarly, but the difference is that {func}`Context.invoke` merely
211 invokes another command with the arguments you provide as a caller,
212 whereas {func}`Context.forward` fills in the arguments from the current
213 command. Both accept the command as the first argument, and everything else
214 is passed onwards as you would expect.
215
216 Example:
217
218 ```{eval-rst}
219 .. click:example::
220
221 cli = click.Group()
222
223 @cli.command()
224 @click.option('--count', default=1)
225 def test(count):
226 click.echo(f'Count: {count}')
227
228 @cli.command()
229 @click.option('--count', default=1)
230 @click.pass_context
231 def dist(ctx, count):
232 ctx.forward(test)
233 ctx.invoke(test, count=42)
234
235 And what it looks like:
236
237 .. click:run::
238
239 invoke(cli, prog_name='cli', args=['dist'])
240 ```
241
242 (forwarding-unknown-options)=
243
244 ## Forwarding Unknown Options
245
246 In some situations, it is interesting to be able to accept all unknown
247 options for further manual processing. Click can generally do that as of
248 Click 4.0, but it has some limitations that lie in the nature of the
249 problem. The support for this is provided through a parser flag called
250 `ignore_unknown_options` which will instruct the parser to collect all
251 unknown options and to put them to the leftover argument instead of
252 triggering a parsing error.
253
254 This can generally be activated in two different ways:
255
256 1. It can be enabled on custom {class}`Command` subclasses by changing
257 the {attr}`~Command.ignore_unknown_options` attribute.
258 2. It can be enabled by changing the attribute of the same name on the
259 context class ({attr}`Context.ignore_unknown_options`). This is best
260 changed through the `context_settings` dictionary on the command.
261
262 For most situations, the easiest solution is the second. Once the behavior
263 is changed, something needs to pick up those leftover options (which at
264 this point are considered arguments). For this again, you have two
265 options:
266
267 1. You can use {func}`pass_context` to get the context passed. This will
268 only work if in addition to {attr}`~Context.ignore_unknown_options`
269 you also set {attr}`~Context.allow_extra_args` as otherwise the
270 command will abort with an error that there are leftover arguments.
271 If you go with this solution, the extra arguments will be collected in
272 {attr}`Context.args`.
273 2. You can attach an {func}`argument` with `nargs` set to `-1` which
274 will eat up all leftover arguments. In this case it's recommended to
275 set the `type` to {data}`UNPROCESSED` to avoid any string processing
276 on those arguments as otherwise they are forced into Unicode strings
277 automatically which is often not what you want.
278
279 In the end, the result looks something like this:
280
281 ```{eval-rst}
282 .. click:example::
283
284 import sys
285 from subprocess import call
286
287 @click.command(context_settings=dict(
288 ignore_unknown_options=True,
289 ))
290 @click.option('-v', '--verbose', is_flag=True, help='Enables verbose mode')
291 @click.argument('timeit_args', nargs=-1, type=click.UNPROCESSED)
292 def cli(verbose, timeit_args):
293 """A fake wrapper around Python's timeit."""
294 cmdline = ['echo', 'python', '-mtimeit'] + list(timeit_args)
295 if verbose:
296 click.echo(f"Invoking: {' '.join(cmdline)}")
297 call(cmdline)
298
299
300 And the final output resembles the following:
301
302 .. click:run::
303
304 invoke(cli, prog_name='cli', args=['--help'])
305 println()
306 invoke(cli, prog_name='cli', args=['-n', '100', 'a = 1; b = 2; a * b'])
307 println()
308 invoke(cli, prog_name='cli', args=['-v', 'a = 1; b = 2; a * b'])
309 ```
310
311 As you can see, Click handles the verbosity flag and everything else
312 ends up in the `timeit_args` variable for further processing, which then
313 for instance, allows invoking a subprocess. There are a few things that
314 are important to know about how this ignoring of unhandled flag happens:
315
316 - Unknown long options are generally ignored and not processed at all.
317 So for instance if `--foo=bar` or `--foo bar` are passed they
318 generally end up like that. Note that because the parser cannot know
319 if an option will accept an argument or not, the `bar` part might be
320 handled as an argument.
321 - Unknown short options might be partially handled and reassembled if
322 necessary. For instance in the above example there is an option
323 called `-v` which enables verbose mode. If the command would be
324 ignored with `-va` then the `-v` part would be handled by Click
325 (as it is known) and `-a` would end up in the leftover parameters
326 for further processing.
327 - Depending on what you plan on doing you might have some success by
328 disabling interspersed arguments
329 ({attr}`~Context.allow_interspersed_args`) which instructs the parser
330 to not allow arguments and options to be mixed. Depending on your
331 situation, this might improve your results.
332
333 Generally, combining the handling of options and arguments from your own
334 commands with those from another application is discouraged, and you
335 should avoid it if possible. It's a much better idea to have
336 everything below a subcommand be forwarded to another application than to
337 handle some arguments yourself.
338
339 ## Managing Resources
340
341 It can be useful to open a resource in a group, to be made available to
342 subcommands. Many types of resources need to be closed or otherwise
343 cleaned up after use. The standard way to do this in Python is by using
344 a context manager with the `with` statement.
345
346 For example, the `Repo` class from {doc}`complex` might actually be
347 defined as a context manager:
348
349 ```python
350 class Repo:
351 def __init__(self, home=None):
352 self.home = os.path.abspath(home or ".")
353 self.db = None
354
355 def __enter__(self):
356 path = os.path.join(self.home, "repo.db")
357 self.db = open_database(path)
358 return self
359
360 def __exit__(self, exc_type, exc_value, tb):
361 self.db.close()
362 ```
363
364 Ordinarily, it would be used with the `with` statement:
365
366 ```python
367 with Repo() as repo:
368 repo.db.query(...)
369 ```
370
371 However, a `with` block in a group would exit and close the database
372 before it could be used by a subcommand.
373
374 Instead, use the context's {meth}`~click.Context.with_resource` method
375 to enter the context manager and return the resource. When the group and
376 any subcommands finish, the context's resources are cleaned up.
377
378 ```python
379 @click.group()
380 @click.option("--repo-home", default=".repo")
381 @click.pass_context
382 def cli(ctx, repo_home):
383 ctx.obj = ctx.with_resource(Repo(repo_home))
384
385 @cli.command()
386 @click.pass_obj
387 def log(obj):
388 # obj is the repo opened in the cli group
389 for entry in obj.db.query(...):
390 click.echo(entry)
391 ```
392
393 If the resource isn't a context manager, usually it can be wrapped in
394 one using something from {mod}`contextlib`. If that's not possible, use
395 the context's {meth}`~click.Context.call_on_close` method to register a
396 cleanup function.
397
398 ```python
399 @click.group()
400 @click.option("--name", default="repo.db")
401 @click.pass_context
402 def cli(ctx, repo_home):
403 ctx.obj = db = open_db(repo_home)
404
405 @ctx.call_on_close
406 def close_db():
407 db.record_use()
408 db.save()
409 db.close()
410 ```
411
412 ```{versionchanged} 8.2
413 `Context.call_on_close` and context managers registered via `Context.with_resource`
414 will be closed when the CLI exits. These were previously not called on exit.
415 ```