Skip to content
Myr

Added a chapter for parameter modifications

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Armin Ronacher · committed by Armin Ronacher · parent c0b076e · Browse files · 1 file+55 added−0 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

1 file+55 added−0 removed

  • other:+55 added−0 removed

1 file+55 added−0 removed

modified:docs/advanced.rst+55 added
60 unmodified lines
61 @cli.command()62 def pop():63 pass6465Parameter 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))118119120Token Normalization121-------------------122123.. versionadded:: 2.0
122 unmodified lines