Skip to content
Myr

advanced.rst

This file

Path

docs/advanced.rst

245 lines · 8.2 KiB

Last changed by

first -> lastArmin Ronacherbefore adoption80e15d5

History of this file

Take it

The walk stopped after 200 commits: lines older than ddf58b2 point at it.

Added license to docs and changelog.Armin Ronacherbefore adoptionddf58b2

lines 1–6why, one step back
1Advanced Patterns
2=================34.. currentmodule:: click56In addition to common functionality that is implemented in the library

Merge pull request #125 from iKevinY/doc-fixesArmin Ronacherbefore adoption1d25afd

line 7why, one step back
7itself, there are countless patterns that can be implemented by extending

Merge pull request #153 from iKevinY/click-renameArmin Ronacherbefore adoption327cfde

line 8why, one step back
8Click. This page should give some insight into what can be accomplished.

Added license to docs and changelog.Armin Ronacherbefore adoptionddf58b2

lines 9–14why, one step back
9
10.. _aliases:1112Command Aliases13---------------14

Merge pull request #109 from iKevinY/doc-fixesArmin Ronacherbefore adoptiond428e69

line 15why, one step back
15Many tools support aliases for commands. For instance, you can configure

Added license to docs and changelog.Armin Ronacherbefore adoptionddf58b2

line 16why, one step back
16``git`` to accept ``git ci`` as alias for ``git commit``. Other tools

Merge pull request #125 from iKevinY/doc-fixesArmin Ronacherbefore adoption1d25afd

line 17why, one step back
17also support auto-discovery for aliases by automatically shortening them.

Added license to docs and changelog.Armin Ronacherbefore adoptionddf58b2

line 18why, one step back
18

Merge pull request #125 from iKevinY/doc-fixesArmin Ronacherbefore adoption1d25afd

line 19why, one step back
19Click does not support this out of the box, but it's very easy to customize

Added license to docs and changelog.Armin Ronacherbefore adoptionddf58b2

lines 20–22why, one step back
20the :class:`Group` or any other :class:`MultiCommand` to provide this
21functionality.22

Merge pull request #109 from iKevinY/doc-fixesArmin Ronacherbefore adoptiond428e69

line 23why, one step back
23As explained in :ref:`custom-multi-commands`, a multi command can provide

Added license to docs and changelog.Armin Ronacherbefore adoptionddf58b2

line 24why, one step back
24two methods: :meth:`~MultiCommand.list_commands` and

Documentation fixesKevin Yapbefore adoption67523af

line 25why, one step back
25:meth:`~MultiCommand.get_command`. In this particular case, you only need

Added license to docs and changelog.Armin Ronacherbefore adoptionddf58b2

line 26why, one step back
26to override the latter as you generally don't want to enumerate the

Documentation fixesKevin Yapbefore adoption67523af

line 27why, one step back
27aliases on the help page in order to avoid confusion.

Added license to docs and changelog.Armin Ronacherbefore adoptionddf58b2

lines 28–29why, one step back
28
29This following example implements a subclass of :class:`Group` that

Merge pull request #125 from iKevinY/doc-fixesArmin Ronacherbefore adoption1d25afd

lines 30–31why, one step back
30accepts a prefix for a command. If there were a command called ``push``,
31it would accept ``pus`` as an alias (so long as it was unique):

Added license to docs and changelog.Armin Ronacherbefore adoptionddf58b2

lines 32–48why, one step back
32
33.. click:example::3435 class AliasedGroup(click.Group):3637 def get_command(self, ctx, cmd_name):38 rv = click.Group.get_command(self, ctx, cmd_name)39 if rv is not None:40 return rv41 matches = [x for x in self.list_commands(ctx)42 if x.startswith(cmd_name)]43 if not matches:44 return None45 elif len(matches) == 1:46 return click.Group.get_command(self, ctx, matches[0])47 ctx.fail('Too many matches: %s' % ', '.join(sorted(matches)))48

Merge pull request #109 from iKevinY/doc-fixesArmin Ronacherbefore adoptiond428e69

line 49why, one step back
49And it can then be used like this:

Added license to docs and changelog.Armin Ronacherbefore adoptionddf58b2

lines 50–64why, one step back
50
51.. click:example::5253 @click.command(cls=AliasedGroup)54 def cli():55 pass5657 @cli.command()58 def push():59 pass6061 @cli.command()62 def pop():63 pass64

Added a chapter for parameter modificationsArmin Ronacherbefore adoptiona08cc28

lines 65–119why, one step back
65Parameter Modifications
66-----------------------6768Parameters (options and arguments) are forwarded to the command callbacks69as you have seen. One common way to prevent a parameter from being passed70to the callback is the `expose_value` argument to a parameter which hides71the parameter entirely. The way this works is that the :class:`Context`72object has a :attr:`~Context.params` attribute which is a dictionary of73all parameters. Whatever is in that dictionary is being passed to the74callbacks.7576This can be used to make up addition parameters. Generally this pattern77is not recommended but in some cases it can be useful. At the very least78it's good to know that the system works this way.7980.. click:example::8182 import urllib8384 def open_url(ctx, param, value):85 if value is not None:86 ctx.params['fp'] = urllib.urlopen(value)87 return value8889 @click.command()90 @click.option('--url', callback=open_url)91 def cli(url, fp=None):92 if fp is not None:93 click.echo('%s: %s' % (url, fp.code))9495In this case the callback returns the URL unchanged but also passes a96second ``fp`` value to the callback. What's more recommended is to pass97the information in a wrapper however:9899.. click:example::100101 import urllib102103 class URL(object):104105 def __init__(self, url, fp):106 self.url = url107 self.fp = fp108109 def open_url(ctx, param, value):110 if value is not None:111 return URL(value, urllib.urlopen(value))112113 @click.command()114 @click.option('--url', callback=open_url)115 def cli(url):116 if url is not None:117 click.echo('%s: %s' % (url.url, url.fp.code))118119

Added example for token normalization.Armin Ronacherbefore adoption8da75f9

lines 120–124why, one step back
120Token Normalization
121-------------------122123.. versionadded:: 2.0124

Merge pull request #153 from iKevinY/click-renameArmin Ronacherbefore adoption327cfde

line 125why, one step back
125Starting with Click 2.0, it's possible to provide a function that is used

Merge pull request #125 from iKevinY/doc-fixesArmin Ronacherbefore adoption1d25afd

lines 126–127why, one step back
126for normalizing tokens. Tokens are option names, choice values, or command
127values. This can be used to implement case insensitive options, for

Added example for token normalization.Armin Ronacherbefore adoption8da75f9

lines 128–129why, one step back
128instance.
129

Merge pull request #125 from iKevinY/doc-fixesArmin Ronacherbefore adoption1d25afd

lines 130–132why, one step back
130In order to use this feature, the context needs to be passed a function that
131performs the normalization of the token. For instance, you could have a132function that converts the token to lowercase:

Added example for token normalization.Armin Ronacherbefore adoption8da75f9

lines 133–135why, one step back
133
134.. click:example::135

defaults -> settingsArmin Ronacherbefore adoption1bc0a19

line 136why, one step back
136 CONTEXT_SETTINGS = dict(token_normalize_func=lambda x: x.lower())

Added example for token normalization.Armin Ronacherbefore adoption8da75f9

line 137why, one step back
137

defaults -> settingsArmin Ronacherbefore adoption1bc0a19

line 138why, one step back
138 @click.command(context_settings=CONTEXT_SETTINGS)

Added example for token normalization.Armin Ronacherbefore adoption8da75f9

lines 139–142why, one step back
139 @click.option('--name', default='Pete')
140 def cli(name):141 click.echo('Name: %s' % name)142

Merge pull request #125 from iKevinY/doc-fixesArmin Ronacherbefore adoption1d25afd

line 143why, one step back
143And how it works on the command line:

Added example for token normalization.Armin Ronacherbefore adoption8da75f9

lines 144–148why, one step back
144
145.. click:run::146147 invoke(cli, prog_name='cli', args=['--NAME=Pete'])148

Added license to docs and changelog.Armin Ronacherbefore adoptionddf58b2

lines 149–151why, one step back
149Invoking Other Commands
150-----------------------151

Merge pull request #109 from iKevinY/doc-fixesArmin Ronacherbefore adoptiond428e69

line 152why, one step back
152Sometimes, it might be interesting to invoke one command from another

Merge pull request #153 from iKevinY/click-renameArmin Ronacherbefore adoption327cfde

line 153why, one step back
153command. This is a pattern that is generally discouraged with Click, but

Documentation fixesKevin Yapbefore adoption67523af

line 154why, one step back
154possible nonetheless. For this, you can use the :func:`Context.invoke`

Added license to docs and changelog.Armin Ronacherbefore adoptionddf58b2

lines 155–156why, one step back
155or :func:`Context.forward` methods.
156

Merge pull request #109 from iKevinY/doc-fixesArmin Ronacherbefore adoptiond428e69

line 157why, one step back
157They work similarly, but the difference is that :func:`Context.invoke` merely

Added license to docs and changelog.Armin Ronacherbefore adoptionddf58b2

lines 158–159why, one step back
158invokes another command with the arguments you provide as a caller,
159whereas :func:`Context.forward` fills in the arguments from the current

Merge pull request #109 from iKevinY/doc-fixesArmin Ronacherbefore adoptiond428e69

lines 160–161why, one step back
160command. Both accept the command as the first argument and everything else
161is passed onwards as you would expect.

Added license to docs and changelog.Armin Ronacherbefore adoptionddf58b2

lines 162–192why, one step back
162
163Example:164165.. click:example::166167 cli = click.Group()168169 @cli.command()170 @click.option('--count', default=1)171 def test(count):172 click.echo('Count: %d' % count)173174 @cli.command()175 @click.option('--count', default=1)176 @click.pass_context177 def dist(ctx, count):178 ctx.forward(test)179 ctx.invoke(test, count=42)180181And what it looks like:182183.. click:run::184185 invoke(cli, prog_name='cli', args=['dist'])186187188.. _callback-evaluation-order:189190Callback Evaluation Order191-------------------------192

Documentation fixesKevin Yapbefore adoption67523af

line 193why, one step back
193Click works a bit differently than some other command line parsers in that

Added license to docs and changelog.Armin Ronacherbefore adoptionddf58b2

lines 194–197why, one step back
194it attempts to reconcile the order of arguments as defined by the
195programmer with the order of arguments as defined by the user before196invoking any callbacks.197

Documentation fixesKevin Yapbefore adoption67523af

line 198why, one step back
198This is an important concept to understand when porting complex

Merge pull request #153 from iKevinY/click-renameArmin Ronacherbefore adoption327cfde

line 199why, one step back
199patterns to Click from optparse or other systems. A parameter

Documentation fixesKevin Yapbefore adoption67523af

line 200why, one step back
200callback invocation in optparse happens as part of the parsing step,

Merge pull request #153 from iKevinY/click-renameArmin Ronacherbefore adoption327cfde

line 201why, one step back
201whereas a callback invocation in Click happens after the parsing.

Added license to docs and changelog.Armin Ronacherbefore adoptionddf58b2

line 202why, one step back
202

Documentation fixesKevin Yapbefore adoption67523af

line 203why, one step back
203The main difference is that in optparse, callbacks are invoked with the raw

Merge pull request #153 from iKevinY/click-renameArmin Ronacherbefore adoption327cfde

line 204why, one step back
204value as it happens, whereas a callback in Click is invoked after the

Added license to docs and changelog.Armin Ronacherbefore adoptionddf58b2

lines 205–206why, one step back
205value has been fully converted.
206

Merge pull request #109 from iKevinY/doc-fixesArmin Ronacherbefore adoptiond428e69

lines 207–210why, one step back
207Generally, the order of invocation is driven by the order in which the user
208provides the arguments to the script; if there is an option called ``--foo``209and an option called ``--bar`` and the user calls it as ``--bar210--foo``, then the callback for ``bar`` will fire before the one for ``foo``.

Added license to docs and changelog.Armin Ronacherbefore adoptionddf58b2

line 211why, one step back
211

two -> threeArmin Ronacherbefore adoption6251839

line 212why, one step back
212There are three exceptions to this rule which are important to know:

Added license to docs and changelog.Armin Ronacherbefore adoptionddf58b2

lines 213–219why, one step back
213
214Eagerness:215 An option can be set to be "eager". All eager parameters are216 evaluated before all non-eager parameters, but again in the order as217 they were provided on the command line by the user.218219 This is important for parameters that execute and exit like ``--help``

Merge pull request #109 from iKevinY/doc-fixesArmin Ronacherbefore adoptiond428e69

line 220why, one step back
220 and ``--version``. Both are eager parameters, but whatever parameter

Added license to docs and changelog.Armin Ronacherbefore adoptionddf58b2

lines 221–224why, one step back
221 comes first on the command line will win and exit the program.
222223Repeated parameters:224 If an option or argument is split up on the command line into multiple

Documentation fixesKevin Yapbefore adoption67523af

lines 225–226why, one step back
225 places because it is repeated -- for instance, ``--exclude foo --include
226 baz --exclude bar`` -- the callback will fire based on the position of

Merge pull request #109 from iKevinY/doc-fixesArmin Ronacherbefore adoptiond428e69

line 227why, one step back
227 the first option. In this case, the callback will fire for

Added license to docs and changelog.Armin Ronacherbefore adoptionddf58b2

lines 228–231why, one step back
228 ``exclude`` and it will be passed both options (``foo`` and
229 ``bar``), then the callback for ``include`` will fire with ``baz``230 only.231

Merge pull request #153 from iKevinY/click-renameArmin Ronacherbefore adoption327cfde

line 232why, one step back
232 Note that even if a parameter does not allow multiple versions, Click

Added license to docs and changelog.Armin Ronacherbefore adoptionddf58b2

line 233why, one step back
233 will still accept the position of the first, but it will ignore every

first -> lastArmin Ronacherbefore adoption80e15d5

line 234why, one step back
234 value except the last. The reason for this is to allow composability

Added license to docs and changelog.Armin Ronacherbefore adoptionddf58b2

lines 235–237why, one step back
235 through shell aliases that set defaults.
236237Missing parameters:

Merge pull request #109 from iKevinY/doc-fixesArmin Ronacherbefore adoptiond428e69

line 238why, one step back
238 If a parameter is not defined on the command line, the callback will

Added license to docs and changelog.Armin Ronacherbefore adoptionddf58b2

lines 239–243why, one step back
239 still fire. This is different from how it works in optparse where
240 undefined values do not fire the callback. Missing parameters fire241 their callbacks at the very end which makes it possible for them to242 default to values from a parameter that came before.243

Documentation fixesKevin Yapbefore adoption67523af

lines 244–245why, one step back
244Most of the time you do not need to be concerned about any of this,
245but it is important to know how it works for some advanced cases.