advanced.rst
This file
Path
docs/advanced.rst
245 lines · 8.2 KiB
Last changed by
first -> lastArmin Ronacherbefore adoption80e15d5
History of this fileTake 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 back1Advanced Patterns2=================34.. currentmodule:: click56In addition to common functionality that is implemented in the libraryMerge pull request #125 from iKevinY/doc-fixesArmin Ronacherbefore adoption1d25afd
line 7why, one step back7itself, there are countless patterns that can be implemented by extendingMerge pull request #153 from iKevinY/click-renameArmin Ronacherbefore adoption327cfde
line 8why, one step back8Click. 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 back910.. _aliases:1112Command Aliases13---------------14Merge pull request #109 from iKevinY/doc-fixesArmin Ronacherbefore adoptiond428e69
line 15why, one step back15Many tools support aliases for commands. For instance, you can configureAdded license to docs and changelog.Armin Ronacherbefore adoptionddf58b2
line 16why, one step back16``git`` to accept ``git ci`` as alias for ``git commit``. Other toolsMerge pull request #125 from iKevinY/doc-fixesArmin Ronacherbefore adoption1d25afd
line 17why, one step back17also support auto-discovery for aliases by automatically shortening them.Added license to docs and changelog.Armin Ronacherbefore adoptionddf58b2
line 18why, one step back18Merge pull request #125 from iKevinY/doc-fixesArmin Ronacherbefore adoption1d25afd
line 19why, one step back19Click does not support this out of the box, but it's very easy to customizeAdded license to docs and changelog.Armin Ronacherbefore adoptionddf58b2
lines 20–22why, one step back20the :class:`Group` or any other :class:`MultiCommand` to provide this21functionality.22Merge pull request #109 from iKevinY/doc-fixesArmin Ronacherbefore adoptiond428e69
line 23why, one step back23As explained in :ref:`custom-multi-commands`, a multi command can provideAdded license to docs and changelog.Armin Ronacherbefore adoptionddf58b2
line 24why, one step back24two methods: :meth:`~MultiCommand.list_commands` andDocumentation fixesKevin Yapbefore adoption67523af
line 25why, one step back25:meth:`~MultiCommand.get_command`. In this particular case, you only needAdded license to docs and changelog.Armin Ronacherbefore adoptionddf58b2
line 26why, one step back26to override the latter as you generally don't want to enumerate theDocumentation fixesKevin Yapbefore adoption67523af
line 27why, one step back27aliases on the help page in order to avoid confusion.Added license to docs and changelog.Armin Ronacherbefore adoptionddf58b2
lines 28–29why, one step back2829This following example implements a subclass of :class:`Group` thatMerge pull request #125 from iKevinY/doc-fixesArmin Ronacherbefore adoption1d25afd
lines 30–31why, one step back30accepts 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 back3233.. 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)))48Merge pull request #109 from iKevinY/doc-fixesArmin Ronacherbefore adoptiond428e69
line 49why, one step back49And it can then be used like this:Added license to docs and changelog.Armin Ronacherbefore adoptionddf58b2
lines 50–64why, one step back5051.. 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 pass64Added a chapter for parameter modificationsArmin Ronacherbefore adoptiona08cc28
lines 65–119why, one step back65Parameter Modifications66-----------------------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))118119Added example for token normalization.Armin Ronacherbefore adoption8da75f9
lines 120–124why, one step back120Token Normalization121-------------------122123.. versionadded:: 2.0124Merge pull request #153 from iKevinY/click-renameArmin Ronacherbefore adoption327cfde
line 125why, one step back125Starting with Click 2.0, it's possible to provide a function that is usedMerge pull request #125 from iKevinY/doc-fixesArmin Ronacherbefore adoption1d25afd
lines 126–127why, one step back126for normalizing tokens. Tokens are option names, choice values, or command127values. This can be used to implement case insensitive options, forAdded example for token normalization.Armin Ronacherbefore adoption8da75f9
lines 128–129why, one step back128instance.129Merge pull request #125 from iKevinY/doc-fixesArmin Ronacherbefore adoption1d25afd
lines 130–132why, one step back130In order to use this feature, the context needs to be passed a function that131performs 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 back133134.. click:example::135defaults -> settingsArmin Ronacherbefore adoption1bc0a19
line 136why, one step back136 CONTEXT_SETTINGS = dict(token_normalize_func=lambda x: x.lower())Added example for token normalization.Armin Ronacherbefore adoption8da75f9
line 137why, one step back137defaults -> settingsArmin Ronacherbefore adoption1bc0a19
line 138why, one step back138 @click.command(context_settings=CONTEXT_SETTINGS)Added example for token normalization.Armin Ronacherbefore adoption8da75f9
lines 139–142why, one step back139 @click.option('--name', default='Pete')140 def cli(name):141 click.echo('Name: %s' % name)142Merge pull request #125 from iKevinY/doc-fixesArmin Ronacherbefore adoption1d25afd
line 143why, one step back143And how it works on the command line:Added example for token normalization.Armin Ronacherbefore adoption8da75f9
lines 144–148why, one step back144145.. click:run::146147 invoke(cli, prog_name='cli', args=['--NAME=Pete'])148Added license to docs and changelog.Armin Ronacherbefore adoptionddf58b2
lines 149–151why, one step back149Invoking Other Commands150-----------------------151Merge pull request #109 from iKevinY/doc-fixesArmin Ronacherbefore adoptiond428e69
line 152why, one step back152Sometimes, it might be interesting to invoke one command from anotherMerge pull request #153 from iKevinY/click-renameArmin Ronacherbefore adoption327cfde
line 153why, one step back153command. This is a pattern that is generally discouraged with Click, butDocumentation fixesKevin Yapbefore adoption67523af
line 154why, one step back154possible nonetheless. For this, you can use the :func:`Context.invoke`Added license to docs and changelog.Armin Ronacherbefore adoptionddf58b2
lines 155–156why, one step back155or :func:`Context.forward` methods.156Merge pull request #109 from iKevinY/doc-fixesArmin Ronacherbefore adoptiond428e69
line 157why, one step back157They work similarly, but the difference is that :func:`Context.invoke` merelyAdded license to docs and changelog.Armin Ronacherbefore adoptionddf58b2
lines 158–159why, one step back158invokes another command with the arguments you provide as a caller,159whereas :func:`Context.forward` fills in the arguments from the currentMerge pull request #109 from iKevinY/doc-fixesArmin Ronacherbefore adoptiond428e69
lines 160–161why, one step back160command. Both accept the command as the first argument and everything else161is passed onwards as you would expect.Added license to docs and changelog.Armin Ronacherbefore adoptionddf58b2
lines 162–192why, one step back162163Example: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-------------------------192Documentation fixesKevin Yapbefore adoption67523af
line 193why, one step back193Click works a bit differently than some other command line parsers in thatAdded license to docs and changelog.Armin Ronacherbefore adoptionddf58b2
lines 194–197why, one step back194it attempts to reconcile the order of arguments as defined by the195programmer with the order of arguments as defined by the user before196invoking any callbacks.197Documentation fixesKevin Yapbefore adoption67523af
line 198why, one step back198This is an important concept to understand when porting complexMerge pull request #153 from iKevinY/click-renameArmin Ronacherbefore adoption327cfde
line 199why, one step back199patterns to Click from optparse or other systems. A parameterDocumentation fixesKevin Yapbefore adoption67523af
line 200why, one step back200callback invocation in optparse happens as part of the parsing step,Merge pull request #153 from iKevinY/click-renameArmin Ronacherbefore adoption327cfde
line 201why, one step back201whereas a callback invocation in Click happens after the parsing.Added license to docs and changelog.Armin Ronacherbefore adoptionddf58b2
line 202why, one step back202Documentation fixesKevin Yapbefore adoption67523af
line 203why, one step back203The main difference is that in optparse, callbacks are invoked with the rawMerge pull request #153 from iKevinY/click-renameArmin Ronacherbefore adoption327cfde
line 204why, one step back204value as it happens, whereas a callback in Click is invoked after theAdded license to docs and changelog.Armin Ronacherbefore adoptionddf58b2
lines 205–206why, one step back205value has been fully converted.206Merge pull request #109 from iKevinY/doc-fixesArmin Ronacherbefore adoptiond428e69
lines 207–210why, one step back207Generally, the order of invocation is driven by the order in which the user208provides 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 back211two -> threeArmin Ronacherbefore adoption6251839
line 212why, one step back212There 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 back213214Eagerness: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 back220 and ``--version``. Both are eager parameters, but whatever parameterAdded license to docs and changelog.Armin Ronacherbefore adoptionddf58b2
lines 221–224why, one step back221 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 multipleDocumentation fixesKevin Yapbefore adoption67523af
lines 225–226why, one step back225 places because it is repeated -- for instance, ``--exclude foo --include226 baz --exclude bar`` -- the callback will fire based on the position ofMerge pull request #109 from iKevinY/doc-fixesArmin Ronacherbefore adoptiond428e69
line 227why, one step back227 the first option. In this case, the callback will fire forAdded license to docs and changelog.Armin Ronacherbefore adoptionddf58b2
lines 228–231why, one step back228 ``exclude`` and it will be passed both options (``foo`` and229 ``bar``), then the callback for ``include`` will fire with ``baz``230 only.231Merge pull request #153 from iKevinY/click-renameArmin Ronacherbefore adoption327cfde
line 232why, one step back232 Note that even if a parameter does not allow multiple versions, ClickAdded license to docs and changelog.Armin Ronacherbefore adoptionddf58b2
line 233why, one step back233 will still accept the position of the first, but it will ignore everyfirst -> lastArmin Ronacherbefore adoption80e15d5
line 234why, one step back234 value except the last. The reason for this is to allow composabilityAdded license to docs and changelog.Armin Ronacherbefore adoptionddf58b2
lines 235–237why, one step back235 through shell aliases that set defaults.236237Missing parameters:Merge pull request #109 from iKevinY/doc-fixesArmin Ronacherbefore adoptiond428e69
line 238why, one step back238 If a parameter is not defined on the command line, the callback willAdded license to docs and changelog.Armin Ronacherbefore adoptionddf58b2
lines 239–243why, one step back239 still fire. This is different from how it works in optparse where240 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.243Documentation fixesKevin Yapbefore adoption67523af
lines 244–245why, one step back244Most 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.