Cleaned up context defaults and documented them.
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 6e98e9b · Browse files · 2 files·+44 added−7 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
2 files+44 added−7 removed
- other:+44 added−7 removed
Provenance
- Commit
7d776de- Tree
1ea4b5c- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
6e98e9b
2 files changed+44 added−7 removed
modified:click/core.py+4 added-7 removed
154 unmodified lines155 obj = parent.obj156 #: the user object stored.157 self.obj = obj158 #: A dictionary (-like object) with defaults for parameters.159+ if default_map is None \160+ and parent is not None \161+ and parent.default_map is not None:162+ default_map = parent.default_map.get(info_name)163 self.default_map = default_map164 165 if terminal_width is None and parent is not None:166 terminal_width = parent.terminal_width228 unmodified lines395 :param parent: the parent context if available.396 :param extra: extra keyword arguments forwarded to the context397 constructor.398 """395- if 'default_map' not in extra:396- default_map = None397- if parent is not None and parent.default_map is not None:398- default_map = parent.default_map.get(info_name)399- extra['default_map'] = default_map400-399 for key, value in iteritems(self.context_defaults or {}):400 if key not in extra:401 extra[key] = value404-402 ctx = Context(self, info_name=info_name, parent=parent, **extra)403 self.parse_args(ctx, args)404 return ctx405 926 unmodified linesmodified:docs/commands.rst+40 added
291 unmodified lines292 'port': 5000293 }294 })295 296+And in action:297+298 .. click:run::299 300 invoke(cli, prog_name='cli', args=['runserver'], default_map={301 'runserver': {302 'port': 5000303 }304 })305+306+Context Defaults307+----------------308+309+.. versionadded:: 2.0310+311+Starting with click 2.0 you can override defaults for contexts not just312+when calling your script, but also in the decorator that declares a313+command. For instance given the previous example which defines a custom314+``default_map`` this can also be accomplished in the decorator now.315+316+This example does the same as the previous example:317+318+.. click:example::319+320+ import click321+322+ CONTEXT_DEFAULTS = dict(323+ default_map={'runserver': {'port': 5000}}324+ )325+326+ @click.group(context_defaults=CONTEXT_DEFAULTS)327+ def cli():328+ pass329+330+ @cli.command()331+ @click.option('--port', default=8000)332+ def runserver(port):333+ click.echo('Serving on http://127.0.0.1:%d/' % port)334+335+ if __name__ == '__main__':336+ cli()337+338+And again the example in action:339+340+.. click:run::341+342+ invoke(cli, prog_name='cli', args=['runserver'])