Changed parameter callback signature.
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 563b325 · Browse files · 7 files·+52 added−12 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
7 files+52 added−12 removed
- tests:+16 added−0 removed
- other:+36 added−12 removed
Provenance
- Commit
bda39db- Tree
64de686- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
563b325
7 files changed+52 added−12 removed
modified:click/core.py+24 added-3 removed
18 unmodified lines19 def batch(iterable, batch_size):20 return list(zip(*repeat(iter(iterable), batch_size)))21 22 23+def invoke_param_callback(callback, ctx, param, value):24+ code = getattr(callback, '__code__', None)25+ args = getattr(code, 'co_argcount', 3)26+27+ if args < 3:28+ from warnings import warn29+ warn(Warning('Invoked legacy parameter callback "%s". The new '30+ 'signature for such callbacks starting with '31+ 'Click 2.0 is (ctx, param, value).'32+ % callback), stacklevel=3)33+ return callback(ctx, value)34+ return callback(ctx, param, value)35+36+37 @contextmanager38 def augment_usage_errors(ctx, param=None):39 """Context manager that attaches extra information to exceptions that40 fly.717 unmodified lines758 intentionally not finalized.759 760 Some settings are supported by both options and arguments.761 762+ .. versionchanged:: 2.0763+ Changed signature for parameter callback to also be passed the764+ parameter. In Click 2.0 the old callback format will still work765+ but it will raise a warning to give you change to migrate the766+ code easier.767+768 :param param_decls: the parameter declarations for this option or769 argument. This is a list of flags or argument770 names.771 :param type: the type that should be used. Either a :class:`ParamType`3 unmodified lines775 :param default: the default value if omitted. This can also be a callable776 in which case it's invoked when the default is needed777 without any arguments.778 :param callback: a callback that should be executed after the parameter759- was matched. This is called as ``fn(ctx, value)`` and760- needs to return the value.779+ was matched. This is called as ``fn(ctx, param,780+ value)`` and needs to return the value.781 :param nargs: the number of arguments to match. If not ``1`` the return782 value is a tuple instead of single value.783 :param metavar: how the value is represented in the help page.784 :param expose_value: if this is `True` then the value is passed onwards109 unmodified lines894 with augment_usage_errors(ctx, param=self):895 value = self.consume_value(ctx, opts)896 value = self.full_process_value(ctx, value)897 if self.callback is not None:878- value = self.callback(ctx, value)898+ value = invoke_param_callback(899+ self.callback, ctx, self, value)900 901 if self.expose_value:902 ctx.params[self.name] = value903 return value, args302 unmodified linesmodified:click/decorators.py+4 added-4 removed
160 unmodified lines161 162 This is equivalent to decorating a function with :func:`option` with163 the following parameters::164 165- def callback(ctx, value):165+ def callback(ctx, param, value):166 if not value:167 ctx.abort()168 169 @click.command()2 unmodified lines172 def dropdb():173 pass174 """175 def decorator(f):176- def callback(ctx, value):176+ def callback(ctx, param, value):177 if not value:178 ctx.abort()179 attrs.setdefault('is_flag', True)180 attrs.setdefault('callback', callback)41 unmodified lines222 def decorator(f):223 prog_name = attrs.pop('prog_name', None)224 message = attrs.pop('message', '%(prog)s, version %(version)s')225 226- def callback(ctx, value):226+ def callback(ctx, param, value):227 if not value:228 return229 prog = prog_name230 if prog is None:38 unmodified lines269 270 All arguments are forwarded to :func:`option`.271 """272 def decorator(f):273- def callback(ctx, value):273+ def callback(ctx, param, value):274 if value:275 echo(ctx.get_help())276 ctx.exit()277 attrs.setdefault('is_flag', True)10 unmodified linesmodified:docs/options.rst+3 added-3 removed
300 unmodified lines301 Here an example for a ``--version`` flag:302 303 .. click:example::304 305- def print_version(ctx, value):305+ def print_version(ctx, param, value):306 if not value:307 return308 click.echo('Version 1.0')309 ctx.exit()24 unmodified lines334 callback:335 336 .. click:example::337 338- def abort_if_false(ctx, value):338+ def abort_if_false(ctx, param, value):339 if not value:340 ctx.abort()341 342 @click.command()200 unmodified lines543 Example:544 545 .. click:example::546 547- def validate_rolls(ctx, value):547+ def validate_rolls(ctx, param, value):548 try:549 rolls, dice = map(int, value.split('d', 2))550 return (dice, rolls)551 except ValueError:17 unmodified linesmodified:examples/aliases/aliases.py+1 added-1 removed
57 unmodified lines58 return click.Group.get_command(self, ctx, matches[0])59 ctx.fail('Too many matches: %s' % ', '.join(sorted(matches)))60 61 62-def read_config(ctx, value):62+def read_config(ctx, param, value):63 """Callback that is used whenever --config is passed. We use this to64 always load the correct config. This means that the config is loaded65 even if the group itself never executes so our aliases stay always66 available.45 unmodified linesmodified:examples/validation/validation.py+1 added-1 removed
3 unmodified lines4 except ImportError:5 import urlparse6 7 8-def validate_count(ctx, value):8+def validate_count(ctx, param, value):9 if value < 0 or value % 2 != 0:10 raise click.BadParameter('Should be a positive, even integer.')11 return value12 32 unmodified linesadded:tests/test_compat.py+16 added
1+import click2+3+4+def test_legacy_callbacks(runner):5+ def legacy_callback(ctx, value):6+ return value.upper()7+8+ @click.command()9+ @click.option('--foo', callback=legacy_callback)10+ def cli(foo):11+ click.echo(foo)12+13+ result = runner.invoke(cli, ['--foo', 'wat'])14+ assert result.exit_code == 015+ assert 'WAT' in result.output16+ assert 'Invoked legacy parameter callback' in result.outputmodified:CHANGES+3 added
18 unmodified lines19 for configs.20 - Added transparent handling for ANSI codes into the :func:`echo`21 function through `colorama`.22 - Added :func:`clear` function.23+- Breaking change: parameter callbacks now get the parameter object24+ passed as second argument. There is legacy support for old callbacks25+ which will warn but still execute the script.26 27 Version 1.128 -----------29 11 unmodified lines