Skip to content
Myr

option callback is invoked when validating prompt value

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

authored by Saif807380 · committed by David Lord · parent 98e471f · Browse files · 5 files+50 added−30 removed
This commit

State

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

Diff stats

5 files+50 added−30 removed

  • tests:+18 added−2 removed
  • other:+32 added−28 removed

5 files+50 added−30 removed

modified:docs/options.rst+12 added-7 removed
826 unmodified lines
827828.. versionchanged:: 2.0829830If you want to apply custom validation logic, you can do this in the831parameter callbacks. These callbacks can both modify values as well as832raise errors if the validation does not work.831parameter callbacks. These callbacks can both modify values as well as832raise errors if the validation does not work. The callback runs after833type conversion. It is called for all sources, including prompts.834835In Click 1.0, you can only raise the :exc:`UsageError` but starting with836Click 2.0, you can also raise the :exc:`BadParameter` error, which has the837added advantage that it will automatically format the error message to838also contain the parameter name.839839Example:840840.. click:example::841842 def validate_rolls(ctx, param, value):843 if isinstance(value, tuple):844 return value845846 try:847 rolls, _, dice = value.partition("d")848 return int(dice), int(rolls)849 except ValueError:850 raise click.BadParameter("format must be 'NdM'")851852 @click.command()851 @click.option("--rolls", callback=validate_rolls, default="1d6")853 @click.option(854 "--rolls", type=click.UNPROCESSED, callback=validate_rolls,855 default="1d6", prompt=True,856 )857 def roll(rolls):858 sides, times = rolls859 click.echo(f"Rolling a {sides}-sided dice {times} time(s)")860856And what it looks like:857861.. click:run::862863 invoke(roll, args=["--rolls=42"])864 println()865 invoke(roll, args=["--rolls=2d12"])866 println()867 invoke(roll, input=["42", "2d12"])868869870.. _optional-value:871
43 unmodified lines
modified:src/click/core.py+17 added-20 removed
1767 unmodified lines
1768 :param required: controls if this is optional or not.1769 :param default: the default value if omitted. This can also be a callable,1770 in which case it's invoked when the default is needed1771 without any arguments.1772 :param callback: a callback that should be executed after the parameter1773 was matched. This is called as ``fn(ctx, param,1774 value)`` and needs to return the value.1772 :param callback: A function to further process or validate the value1773 after type conversion. It is called as ``f(ctx, param, value)``1774 and must return the value. It is called for all sources,1775 including prompts.1776 :param nargs: the number of arguments to match. If not ``1`` the return1777 value is a tuple instead of single value. The default for1778 nargs is ``1`` (except if the type is a tuple, then it's1779 the arity of the tuple). If ``nargs=-1``, all remaining
13 unmodified lines
1793 of :class:`~click.shell_completion.CompletionItem` or a list of1794 strings.17951796 .. versionchanged:: 8.01797 ``process_value`` validates required parameters and bounded1798 ``nargs``, and invokes the parameter callback before returning1799 the value. This allows the callback to validate prompts.1800 ``full_process_value`` is removed.18011802 .. versionchanged:: 8.01803 ``autocompletion`` is renamed to ``shell_complete`` and has new1804 semantics described above. The old name is deprecated and will1805 be removed in 8.1, until then it will be wrapped to match the1806 new requirements.
207 unmodified lines
2014 return tuple(_convert(x, level - 1) for x in value)20152016 return _convert(value, (self.nargs != 1) + bool(self.multiple))20172011 def process_value(self, ctx, value):2012 """Given a value and context this runs the logic to convert the2013 value as necessary.2014 """2015 # If the value we were given is None we do nothing. This way2016 # code that calls this can easily figure out if something was2017 # not provided. Otherwise it would be converted into an empty2018 # tuple for multiple invocations which is inconvenient.2019 if value is not None:2020 return self.type_cast_value(ctx, value)20212018 def value_is_missing(self, value):2019 if value is None:2020 return True2021 if (self.nargs != 1 or self.multiple) and value == ():2022 return True2023 return False20242029 def full_process_value(self, ctx, value):2030 value = self.process_value(ctx, value)2025 def process_value(self, ctx, value):2026 if value is not None:2027 value = self.type_cast_value(ctx, value)20282029 if self.required and self.value_is_missing(value):2030 raise MissingParameter(ctx=ctx, param=self)2031
13 unmodified lines
2045 f"Argument {self.name!r} takes {self.nargs} values but"2046 f" {len(value)} {were} given."2047 )20482049 if self.callback is not None:2050 value = self.callback(ctx, self, value)20512052 return value20532054 def resolve_envvar_value(self, ctx):2055 if self.envvar is None:
24 unmodified lines
2080 value, source = self.consume_value(ctx, opts)2081 ctx.set_parameter_source(self.name, source)20822083 try:2084 value = self.full_process_value(ctx, value)20852086 if self.callback is not None:2087 value = self.callback(ctx, self, value)2084 value = self.process_value(ctx, value)2085 except Exception:2086 if not ctx.resilient_parsing:2087 raise2088
514 unmodified lines
modified:tests/test_arguments.py+1 added-1 removed
226 unmodified lines
227def test_missing_argument_string_cast():228 ctx = click.Context(click.Command(""))229230 with pytest.raises(click.MissingParameter) as excinfo:231 click.Argument(["a"], required=True).full_process_value(ctx, None)231 click.Argument(["a"], required=True).process_value(ctx, None)232233 assert str(excinfo.value) == "missing parameter: a"234235
139 unmodified lines
modified:tests/test_options.py+17 added-1 removed
374 unmodified lines
375 result = runner.invoke(cmd, ["--foo", "42"])376 assert result.output == "42\n"377378379def test_callback_validates_prompt(runner, monkeypatch):380 def validate(ctx, param, value):381 if value < 0:382 raise click.BadParameter("should be positive")383384 return value385386 @click.command()387 @click.option("-a", type=int, callback=validate, prompt=True)388 def cli(a):389 click.echo(a)390391 result = runner.invoke(cli, input="-12\n60\n")392 assert result.output == "A: -12\nError: should be positive\nA: 60\n60\n"393394395def test_winstyle_options(runner):396 @click.command()397 @click.option("/debug;/no-debug", help="Enables or disables debug mode.")398 def cmd(debug):
25 unmodified lines
424def test_missing_option_string_cast():425 ctx = click.Context(click.Command(""))426427 with pytest.raises(click.MissingParameter) as excinfo:412 click.Option(["-a"], required=True).full_process_value(ctx, None)428 click.Option(["-a"], required=True).process_value(ctx, None)429430 assert str(excinfo.value) == "missing parameter: a"431432
291 unmodified lines
modified:CHANGES.rst+3 added-1 removed
165 unmodified lines
166- Control the location of the temporary directory created by167 ``CLIRunner.isolated_filesystem`` by passing ``temp_dir``. A custom168 directory will not be removed automatically. :issue:`395`169- ``click.confirm()`` will prompt until input is given if called with170 ``default=None``. :issue:`#1381`170 ``default=None``. :issue:`1381`171- Option prompts validate the value with the option's callback in172 addition to its type. :issue:`457`173174175Version 7.1.2176-------------
635 unmodified lines