Skip to content
Myr

refactor type_cast_value

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

default value is validated against multiple and nargs in __init__

authored by David Lord · committed by David Lord · parent 82a83fd · Browse files · 5 files+176 added−101 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+176 added−101 removed

  • tests:+46 added−33 removed
  • other:+130 added−68 removed

5 files+176 added−101 removed

modified:src/click/core.py+114 added-64 removed
3 unmodified lines
4import sys5import typing as t6from contextlib import contextmanager7from contextlib import ExitStack8from functools import partial9from functools import update_wrapper10from gettext import gettext as _11from gettext import ngettext12from itertools import repeat
1782 unmodified lines
1795 rv.update(source.list_commands(ctx))1796 return sorted(rv)179717981799def _check_iter(value):1800 """Check if the value is iterable but not a string. Raises a type1801 error, or return an iterator over the value.1802 """1803 if isinstance(value, str):1804 raise TypeError18051806 return iter(value)180718081809class Parameter:1810 r"""A parameter to a command comes in two versions: they are either1811 :class:`Option`\s or :class:`Argument`\s. Other subclasses are currently1812 not supported by design as some of the internals for parsing are
76 unmodified lines
1889 required=False,1890 default=None,1891 callback=None,1892 nargs=None,1893 multiple=False,1894 metavar=None,1895 expose_value=True,1896 is_eager=False,1897 envvar=None,
16 unmodified lines
19141915 self.required = required1916 self.callback = callback1917 self.nargs = nargs1906 self.multiple = False1918 self.multiple = multiple1919 self.expose_value = expose_value1920 self.default = default1921 self.is_eager = is_eager1922 self.metavar = metavar
27 unmodified lines
1950 return out19511952 self._custom_shell_complete = shell_complete19531954 if __debug__:1955 if self.type.is_composite and nargs != self.type.arity:1956 raise ValueError(1957 f"'nargs' must be {self.type.arity} (or None) for"1958 f" type {self.type!r}, but it was {nargs}."1959 )19601961 # Skip no default or callable default.1962 check_default = default if not callable(default) else None19631964 if check_default is not None:1965 if multiple:1966 try:1967 # Only check the first value against nargs.1968 check_default = next(_check_iter(check_default), None)1969 except TypeError:1970 raise ValueError(1971 "'default' must be a list when 'multiple' is true."1972 ) from None19731974 # Can be None for multiple with empty default.1975 if nargs != 1 and check_default is not None:1976 try:1977 _check_iter(check_default)1978 except TypeError:1979 if multiple:1980 message = (1981 "'default' must be a list of lists when 'multiple' is"1982 " true and 'nargs' != 1."1983 )1984 else:1985 message = "'default' must be a list when 'nargs' != 1."19861987 raise ValueError(message) from None19881989 if nargs > 1 and len(check_default) != nargs:1990 subject = "item length" if multiple else "length"1991 raise ValueError(1992 f"'default' {subject} must match nargs={nargs}."1993 )19941995 def to_info_dict(self):1996 """Gather information that could be useful for a tool generating1997 user-facing documentation.1998
84 unmodified lines
20832084 return value, source20852086 def type_cast_value(self, ctx, value):2034 """Given a value this runs it properly through the type system.2035 This automatically handles things like `nargs` and `multiple` as2036 well as composite types.2087 """Convert and validate a value against the option's2088 :attr:`type`, :attr:`multiple`, and :attr:`nargs`.2089 """2090 if value is None:2091 return () if self.multiple or self.nargs == -1 else None20922041 if self.type.is_composite:2042 if self.nargs <= 1:2043 raise TypeError(2044 "Attempted to invoke composite type but nargs has"2045 f" been set to {self.nargs}. This is not supported;"2046 " nargs needs to be set to a fixed value > 1."2047 )2093 def check_iter(value):2094 try:2095 return _check_iter(value)2096 except TypeError:2097 # This should only happen when passing in args manually,2098 # the parser should construct an iterable when parsing2099 # the command line.2100 raise BadParameter(2101 _("Value must be an iterable."), ctx=ctx, param=self2102 ) from None21032049 if self.multiple:2050 return tuple(self.type(x, self, ctx) for x in value)2104 if self.nargs == 1 or self.type.is_composite:2105 convert = partial(self.type, param=self, ctx=ctx)2106 elif self.nargs == -1:21072052 return self.type(value, self, ctx)2108 def convert(value):2109 return tuple(self.type(x, self, ctx) for x in check_iter(value))21102054 def _convert(value, level):2055 if level == 0:2056 return self.type(value, self, ctx)2111 else: # nargs > 121122058 try:2059 iter_value = iter(value)2060 except TypeError:2061 raise TypeError(2062 "Value for parameter with multiple = True or nargs > 1"2063 " should be an iterable."2064 )2113 def convert(value):2114 value = tuple(check_iter(value))21152066 return tuple(_convert(x, level - 1) for x in iter_value)2116 if len(value) != self.nargs:2117 raise BadParameter(2118 ngettext(2119 "Takes {nargs} values but 1 was given.",2120 "Takes {nargs} values but {len} were given.",2121 len(value),2122 ).format(nargs=self.nargs, len=len(value)),2123 ctx=ctx,2124 param=self,2125 )21262068 return _convert(value, (self.nargs != 1) + bool(self.multiple))2127 return tuple(self.type(x, self, ctx) for x in value)21282129 if self.multiple:2130 return tuple(convert(x) for x in check_iter(value))21312132 return convert(value)21332134 def value_is_missing(self, value):2135 if value is None:2136 return True21372138 if (self.nargs != 1 or self.multiple) and value == ():2139 return True21402141 return False21422143 def process_value(self, ctx, value):2144 if value is not None:
1 unmodified line
21462147 if self.required and self.value_is_missing(value):2148 raise MissingParameter(ctx=ctx, param=self)21492084 # For bounded nargs (!= -1), validate the number of values.2085 if (2086 not ctx.resilient_parsing2087 and self.nargs > 12088 and isinstance(value, (tuple, list))2089 and (2090 any(len(v) != self.nargs for v in value)2091 if self.multiple2092 else len(value) != self.nargs2093 )2094 ):2095 ctx.fail(2096 ngettext(2097 "Argument {name!r} takes {nargs} values but 1 was given.",2098 "Argument {name!r} takes {nargs} values but {len} were given.",2099 len(value),2100 ).format(name=self.name, nargs=self.nargs, len=len(value))2101 )21022150 if self.callback is not None:2151 value = self.callback(ctx, self, value)21522153 return value
142 unmodified lines
2296 show_envvar=False,2297 **attrs,2298 ):2299 default_is_missing = attrs.get("default", _missing) is _missing2253 super().__init__(param_decls, type=type, **attrs)2300 super().__init__(param_decls, type=type, multiple=multiple, **attrs)23012302 if prompt is True:2303 prompt_text = self.name.replace("_", " ").capitalize()2304 elif prompt is False:
48 unmodified lines
2353 self.type = IntRange(min=0)2354 if default_is_missing:2355 self.default = 023562310 self.multiple = multiple2357 self.allow_from_autoenv = allow_from_autoenv2358 self.help = help2359 self.show_default = show_default2360 self.show_choices = show_choices2361 self.show_envvar = show_envvar23622317 # Sanity check for stuff we don't support2363 if __debug__:2319 if self.nargs < 0:2320 raise TypeError("Options cannot have nargs < 0")2364 if self.nargs == -1:2365 raise TypeError("nargs=-1 is not supported for options.")23662367 if self.prompt and self.is_flag and not self.is_bool_flag:2322 raise TypeError("Cannot prompt for flags that are not bools.")2368 raise TypeError("'prompt' is not valid for non-boolean flag.")23692370 if not self.is_bool_flag and self.secondary_opts:2324 raise TypeError("Got secondary option for non boolean flag.")2371 raise TypeError("Secondary flag is not valid for non-boolean flag.")23722373 if self.is_bool_flag and self.hide_input and self.prompt is not None:2326 raise TypeError("Hidden input does not work with boolean flag prompts.")2374 raise TypeError(2375 "'prompt' with 'hide_input' is not valid for boolean flag."2376 )23772378 if self.count:2379 if self.multiple:2329 raise TypeError(2330 "Options cannot be multiple and count at the same time."2331 )2332 elif self.is_flag:2333 raise TypeError(2334 "Options cannot be count and flags at the same time."2335 )2380 raise TypeError("'count' is not valid with 'multiple'.")23812382 if self.is_flag:2383 raise TypeError("'count' is not valid with 'is_flag'.")23842385 def to_info_dict(self):2386 info_dict = super().to_info_dict()2387 info_dict.update(2388 help=self.help,
266 unmodified lines
2655 required = False2656 else:2657 required = attrs.get("nargs", 1) > 026582659 if "multiple" in attrs:2660 raise TypeError("__init__() got an unexpected keyword argument 'multiple'.")26612662 super().__init__(param_decls, required=required, **attrs)26632613 if self.default is not None and self.nargs < 0:2614 raise TypeError(2615 "nargs=-1 in combination with a default value is not supported."2616 )2664 if __debug__:2665 if self.default is not None and self.nargs == -1:2666 raise TypeError("'default' is not supported for nargs=-1.")26672668 @property2669 def human_readable_name(self):2670 if self.metavar is not None:
38 unmodified lines
modified:src/click/types.py+13 added-4 removed
862 unmodified lines
863 def arity(self):864 return len(self.types)865866 def convert(self, value, param, ctx):867 if len(value) != len(self.types):868 raise TypeError(869 "It would appear that nargs is set to conflict with the"870 " composite type arity."867 len_type = len(self.types)868 len_value = len(value)869870 if len_value != len_type:871 self.fail(872 ngettext(873 "{len_type} values are required, but {len_value} was given.",874 "{len_type} values are required, but {len_value} were given.",875 len_value,876 ).format(len_type=len_type, len_value=len_value),877 param=param,878 ctx=ctx,879 )880881 return tuple(ty(x, param, ctx) for ty, x in zip(self.types, value))882883884def convert_type(ty, default=None):
93 unmodified lines
modified:tests/test_arguments.py+13 added-21 removed
20 unmodified lines
21def test_argument_unbounded_nargs_cant_have_default(runner):22 with pytest.raises(TypeError, match="nargs=-1"):2324 @click.command()25 @click.argument("src", nargs=-1, default=42)25 @click.argument("src", nargs=-1, default=["42"])26 def copy(src):27 pass2829
136 unmodified lines
166@pytest.mark.parametrize(167 ("nargs", "value", "expect"),168 [169 (2, "", None),170 (2, "a", "Argument 'arg' takes 2 values but 1 was given."),170 (2, "a", "Takes 2 values but 1 was given."),171 (2, "a b", ("a", "b")),172 (2, "a b c", "Argument 'arg' takes 2 values but 3 were given."),172 (2, "a b c", "Takes 2 values but 3 were given."),173 (-1, "a b c", ("a", "b", "c")),174 (-1, "", ()),175 ],176)
10 unmodified lines
187188 result = runner.invoke(cmd, env={"X": value}, standalone_mode=False)189190 if isinstance(expect, str):191 assert expect in str(result.exception)191 assert isinstance(result.exception, click.BadParameter)192 assert expect in result.exception.format_message()193 else:194 assert result.return_value == expect195196
116 unmodified lines
313 def copy(x):314 click.echo(x)315316316@pytest.mark.parametrize(317 ("value", "code", "output"),318 [319 ((), 2, "Argument 'arg' takes 2 values but 0 were given."),320 (("a",), 2, "Argument 'arg' takes 2 values but 1 was given."),321 (("a", "b"), 0, "len 2"),322 (("a", "b", "c"), 2, "Argument 'arg' takes 2 values but 3 were given."),323 ],324)325def test_nargs_default(runner, value, code, output):326 @click.command()327 @click.argument("arg", nargs=2, default=value)328 def cmd(arg):329 click.echo(f"len {len(arg)}")317def test_multiple_not_allowed():318 with pytest.raises(TypeError, match="multiple"):319 click.Argument(["a"], multiple=True)320331 result = runner.invoke(cmd)332 assert result.exit_code == code333 assert output in result.output321322@pytest.mark.parametrize("value", [(), ("a",), ("a", "b", "c")])323def test_nargs_bad_default(runner, value):324 with pytest.raises(ValueError, match="nargs=2"):325 click.Argument(["a"], nargs=2, default=value)326327328def test_subcommand_help(runner):329 @click.group()330 @click.argument("name")331 @click.argument("val")
35 unmodified lines
modified:tests/test_options.py+33 added-12 removed
31 unmodified lines
32 assert "'--foo'" in message333435def test_invalid_nargs(runner):36 with pytest.raises(TypeError, match="nargs < 0"):36 with pytest.raises(TypeError, match="nargs=-1"):3738 @click.command()39 @click.option("--foo", nargs=-1)40 def cli(foo):
75 unmodified lines
116 assert result.exception117 assert "Error: Missing option '-m' / '--message'." in result.output118119120def test_multiple_bad_default(runner):121 @click.command()122 @click.option("--flags", multiple=True, default=False)123 def cli(flags):124 pass120@pytest.mark.parametrize(121 ("multiple", "nargs", "default"),122 [123 (True, 1, []),124 (True, 1, [1]),125 # (False, -1, []),126 # (False, -1, [1]),127 (False, 2, [1, 2]),128 # (True, -1, [[]]),129 # (True, -1, []),130 # (True, -1, [[1]]),131 (True, 2, []),132 (True, 2, [[1, 2]]),133 ],134)135def test_init_good_default_list(runner, multiple, nargs, default):136 click.Option(["-a"], multiple=multiple, nargs=nargs, default=default)137126 result = runner.invoke(cli, [])127 assert result.exception128 assert (129 "Value for parameter with multiple = True or nargs > 1 should be an iterable."130 in result.exception.args131 )138139@pytest.mark.parametrize(140 ("multiple", "nargs", "default"),141 [142 (True, 1, 1),143 # (False, -1, 1),144 (False, 2, [1]),145 (True, 2, [[1]]),146 ],147)148def test_init_bad_default_list(runner, multiple, nargs, default):149 type = (str, str) if nargs == 2 else None150151 with pytest.raises(ValueError, match="default"):152 click.Option(["-a"], type=type, multiple=multiple, nargs=nargs, default=default)153154155def test_empty_envvar(runner):156 @click.command()157 @click.option("--mypath", type=click.Path(exists=True), envvar="MYPATH")158 def cli(mypath):
600 unmodified lines
modified:CHANGES.rst+3 added
210 unmodified lines
211- Fix issues with ``CliRunner`` output when using ``echo_stdin=True``.212 :issue:`1101`213- Fix a bug of ``click.utils.make_default_short_help`` for which the214 returned string could be as long as ``max_width + 3``. :issue:`1849`215- When defining a parameter, ``default`` is validated with216 ``multiple`` and ``nargs``. More validation is done for values being217 processed as well. :issue:`1806`218219220Version 7.1.2221-------------
635 unmodified lines