Skip to content
Myr

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

2 files+44 added−7 removed

modified:click/core.py+4 added-7 removed
154 unmodified lines
155 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_map164165 if terminal_width is None and parent is not None:166 terminal_width = parent.terminal_width
228 unmodified lines
395 :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_map400399 for key, value in iteritems(self.context_defaults or {}):400 if key not in extra:401 extra[key] = value404402 ctx = Context(self, info_name=info_name, parent=parent, **extra)403 self.parse_args(ctx, args)404 return ctx405
926 unmodified lines
modified:docs/commands.rst+40 added
291 unmodified lines
292 'port': 5000293 }294 })295296And in action:297298.. click:run::299300 invoke(cli, prog_name='cli', args=['runserver'], default_map={301 'runserver': {302 'port': 5000303 }304 })305306Context Defaults307----------------308309.. versionadded:: 2.0310311Starting with click 2.0 you can override defaults for contexts not just312when calling your script, but also in the decorator that declares a313command. For instance given the previous example which defines a custom314``default_map`` this can also be accomplished in the decorator now.315316This example does the same as the previous example:317318.. click:example::319320 import click321322 CONTEXT_DEFAULTS = dict(323 default_map={'runserver': {'port': 5000}}324 )325326 @click.group(context_defaults=CONTEXT_DEFAULTS)327 def cli():328 pass329330 @cli.command()331 @click.option('--port', default=8000)332 def runserver(port):333 click.echo('Serving on http://127.0.0.1:%d/' % port)334335 if __name__ == '__main__':336 cli()337338And again the example in action:339340.. click:run::341342 invoke(cli, prog_name='cli', args=['runserver'])