Skip to content
Myr

Added support for tuple types. This fixes #239

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 dd0635c · Browse files · 7 files+143 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

7 files+143 added−7 removed

  • tests:+36 added−0 removed
  • other:+107 added−7 removed

7 files+143 added−7 removed

modified:click/__init__.py+4 added-4 removed
22 unmodified lines
23 command, group, argument, option, confirmation_option, \24 password_option, version_option, help_option2526# Types27from .types import ParamType, File, Path, Choice, IntRange, STRING, INT, \28 FLOAT, BOOL, UUID, UNPROCESSED27from .types import ParamType, File, Path, Choice, IntRange, Tuple, \28 STRING, INT, FLOAT, BOOL, UUID, UNPROCESSED2930# Utilities31from .utils import echo, get_binary_stream, get_text_stream, open_file, \32 format_filename, get_app_dir
24 unmodified lines
57 'argument', 'option', 'confirmation_option', 'password_option',58 'version_option', 'help_option',5960 # Types61 'ParamType', 'File', 'Path', 'Choice', 'IntRange', 'STRING', 'INT',62 'FLOAT', 'BOOL', 'UUID', 'UNPROCESSED',61 'ParamType', 'File', 'Path', 'Choice', 'IntRange', 'Tuple', 'STRING',62 'INT', 'FLOAT', 'BOOL', 'UUID', 'UNPROCESSED',6364 # Utilities65 'echo', 'get_binary_stream', 'get_text_stream', 'open_file',66 'format_filename', 'get_app_dir',
19 unmodified lines
modified:click/core.py+26 added-3 removed
1164 unmodified lines
1165 was matched. This is called as ``fn(ctx, param,1166 value)`` and needs to return the value. Before Click1167 2.0, the signature was ``(ctx, value)``.1168 :param nargs: the number of arguments to match. If not ``1`` the return1169 value is a tuple instead of single value.1169 value is a tuple instead of single value. The default for1170 nargs is ``1`` (except if the type is a tuple, then it's1171 the arity of the tuple).1172 :param metavar: how the value is represented in the help page.1173 :param expose_value: if this is `True` then the value is passed onwards1174 to the command callback and stored on the context,1175 otherwise it's skipped.
5 unmodified lines
1181 """1182 param_type_name = 'parameter'11831184 def __init__(self, param_decls=None, type=None, required=False,1183 default=None, callback=None, nargs=1, metavar=None,1185 default=None, callback=None, nargs=None, metavar=None,1186 expose_value=True, is_eager=False, envvar=None):1187 self.name, self.opts, self.secondary_opts = \1188 self._parse_decls(param_decls or (), expose_value)11891190 self.type = convert_type(type, default)11911192 # Default nargs to what the type tells us if we have that1193 # information available.1194 if nargs is None:1195 if self.type.is_composite:1196 nargs = self.type.arity1197 else:1198 nargs = 111991200 self.required = required1201 self.callback = callback1202 self.nargs = nargs1203 self.multiple = False
41 unmodified lines
1245 return value12461247 def type_cast_value(self, ctx, value):1248 """Given a value this runs it properly through the type system.1237 This automatically handles things like `nargs` and `multiple`.1249 This automatically handles things like `nargs` and `multiple` as1250 well as composite types.1251 """1252 if self.type.is_composite:1253 if self.nargs <= 1:1254 raise TypeError('Attempted to invoke composite type '1255 'but nargs has been set to %s. This is '1256 'not supported; nargs needs to be set to '1257 'a fixed value > 1.' % self.nargs)1258 if self.multiple:1259 return tuple(self.type(x or (), self, ctx) for x in value or ())1260 return self.type(value or (), self, ctx)12611262 def _convert(value, level):1263 if level == 0:1264 return self.type(value, self, ctx)1265 return tuple(_convert(x, level - 1) for x in value or ())
395 unmodified lines
modified:click/types.py+39 added
18 unmodified lines
19 * it needs to be able to deal with param and context being `None`.20 This can be the case when the object is used with prompt21 inputs.22 """23 is_composite = False2425 #: the descriptive name of this type26 name = None27
39 unmodified lines
67 """Helper method to fail with an invalid value message."""68 raise BadParameter(message, ctx=ctx, param=param)697071class CompositeParamType(ParamType):72 is_composite = True7374 @property75 def arity(self):76 raise NotImplementedError()777879class FuncParamType(ParamType):8081 def __init__(self, func):82 self.name = func.__name__
330 unmodified lines
413414 return rv415416417class Tuple(CompositeParamType):418 """The default behavior of Click is to apply a type on a value directly.419 This works well in most cases, except for when `nargs` is set to a fixed420 count and differnt types should be used for different items. In this421 case the :class:`Tuple` type can be used. This type can only be used422 if `nargs` is set to a fixed number.423424 For more information see :ref:`tuple-type`.425426 This can be selected by using a Python tuple literal as a type.427428 :param types: a list of types that should be used for the tuple items.429 """430431 def __init__(self, types):432 self.types = [convert_type(ty) for ty in types]433434 @property435 def arity(self):436 return len(self.types)437438 def convert(self, value, param, ctx):439 if len(value) != len(self.types):440 raise TypeError('It would appear that nargs is set to conflict '441 'with the composite type arity.')442 return tuple(ty(x, param, ctx) for ty, x in zip(self.types, value))443444445def convert_type(ty, default=None):446 """Converts a callable or python ty into the most appropriate param447 ty.448 """449 if isinstance(ty, tuple):450 return Tuple(ty)451 if isinstance(ty, ParamType):452 return ty453 guessed_type = False454 if ty is None and default is not None:
60 unmodified lines
modified:docs/api.rst+2 added
127 unmodified lines
128.. autoclass:: Choice129130.. autoclass:: IntRange131132.. autoclass:: Tuple133134.. autoclass:: ParamType135 :members:136137Exceptions
40 unmodified lines
modified:docs/options.rst+36 added
53 unmodified lines
54.. click:run::5556 invoke(findme, args=['--pos', '2.0', '3.0'])5758.. _tuple-type:5960Tuples as Multi Value Options61-----------------------------6263.. versionadded:: 4.06465As you can see that by using `nargs` set to a specific number each item in66the resulting tuple is of the same type. This might not be what you want.67Commonly you might want to use different types for different indexes in68the tuple. For this you can directly specify a tuple as type:6970.. click:example::7172 @click.command()73 @click.option('--item', type=(unicode, int))74 def putitem(item):75 click.echo('name=%s id=%d' % item)7677And on the command line:7879.. click:run::8081 invoke(putitem, args=['--item', 'peter', '1338'])8283By using a tuple literal as type, `nargs` gets automatically set to the84length of the tuple and the :class:`click.Tuple` type is automatically85used. The above example is thus equivalent to this:8687.. click:example::8889 @click.command()90 @click.option('--item', nargs=2, type=click.Tuple([unicode, int]))91 def putitem(item):92 click.echo('name=%s id=%d' % item)9394Multiple Options95----------------9697Similarly to ``nargs``, there is also the case of wanting to support a
554 unmodified lines
modified:tests/test_arguments.py+21 added
32 unmodified lines
33 'point=1/2',34 ]353637def test_nargs_tup_composite(runner):38 variations = [39 dict(type=(unicode, int)),40 dict(type=click.Tuple([unicode, int])),41 dict(nargs=2, type=click.Tuple([unicode, int])),42 dict(nargs=2, type=(unicode, int)),43 ]4445 for opts in variations:46 @click.command()47 @click.argument('item', **opts)48 def copy(item):49 click.echo('name=%s id=%d' % item)5051 result = runner.invoke(copy, ['peter', '1'])52 assert not result.exception53 assert result.output.splitlines() == [54 'name=peter id=1',55 ]565758def test_nargs_err(runner):59 @click.command()60 @click.argument('x')61 def copy(x):
151 unmodified lines
modified:tests/test_options.py+15 added
44 unmodified lines
45 else:46 assert False, 'Expected a type error because of an invalid option.'474849def test_nargs_tup_composite_mult(runner):50 @click.command()51 @click.option('--item', type=(unicode, int), multiple=True)52 def copy(item):53 for item in item:54 click.echo('name=%s id=%d' % item)5556 result = runner.invoke(copy, ['--item', 'peter', '1', '--item', 'max', '2'])57 assert not result.exception58 assert result.output.splitlines() == [59 'name=peter id=1',60 'name=max id=2',61 ]626364def test_counting(runner):65 @click.command()66 @click.option('-v', count=True, help='Verbosity',67 type=click.IntRange(0, 3))
226 unmodified lines