summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorArmin Ronacher <armin.ronacher@active-4.com>2014-06-05 16:45:41 +0600
committerArmin Ronacher <armin.ronacher@active-4.com>2014-06-05 16:45:41 +0600
commit7d776de4eb89a58058567d9992371f58c71c3ad4 (patch)
tree1ea4b5cb73628e1cc514dcdb13ddf94374e9a993
parent6e98e9bfc31a2e360addd3e443eb93afb384e099 (diff)
downloadclick-7d776de4eb89a58058567d9992371f58c71c3ad4.tar.gz
Cleaned up context defaults and documented them.
-rw-r--r--click/core.py11
-rw-r--r--docs/commands.rst40
2 files changed, 44 insertions, 7 deletions
diff --git a/click/core.py b/click/core.py
index 9e59b41..b168e52 100644
--- a/click/core.py
+++ b/click/core.py
@@ -156,6 +156,10 @@ class Context(object):
#: the user object stored.
self.obj = obj
#: A dictionary (-like object) with defaults for parameters.
+ if default_map is None \
+ and parent is not None \
+ and parent.default_map is not None:
+ default_map = parent.default_map.get(info_name)
self.default_map = default_map
if terminal_width is None and parent is not None:
@@ -392,16 +396,9 @@ class BaseCommand(object):
:param extra: extra keyword arguments forwarded to the context
constructor.
"""
- if 'default_map' not in extra:
- default_map = None
- if parent is not None and parent.default_map is not None:
- default_map = parent.default_map.get(info_name)
- extra['default_map'] = default_map
-
for key, value in iteritems(self.context_defaults or {}):
if key not in extra:
extra[key] = value
-
ctx = Context(self, info_name=info_name, parent=parent, **extra)
self.parse_args(ctx, args)
return ctx
diff --git a/docs/commands.rst b/docs/commands.rst
index 6cad462..620f56f 100644
--- a/docs/commands.rst
+++ b/docs/commands.rst
@@ -293,6 +293,8 @@ Example usage:
}
})
+And in action:
+
.. click:run::
invoke(cli, prog_name='cli', args=['runserver'], default_map={
@@ -300,3 +302,41 @@ Example usage:
'port': 5000
}
})
+
+Context Defaults
+----------------
+
+.. versionadded:: 2.0
+
+Starting with click 2.0 you can override defaults for contexts not just
+when calling your script, but also in the decorator that declares a
+command. For instance given the previous example which defines a custom
+``default_map`` this can also be accomplished in the decorator now.
+
+This example does the same as the previous example:
+
+.. click:example::
+
+ import click
+
+ CONTEXT_DEFAULTS = dict(
+ default_map={'runserver': {'port': 5000}}
+ )
+
+ @click.group(context_defaults=CONTEXT_DEFAULTS)
+ def cli():
+ pass
+
+ @cli.command()
+ @click.option('--port', default=8000)
+ def runserver(port):
+ click.echo('Serving on http://127.0.0.1:%d/' % port)
+
+ if __name__ == '__main__':
+ cli()
+
+And again the example in action:
+
+.. click:run::
+
+ invoke(cli, prog_name='cli', args=['runserver'])