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
Provenance
- Commit
f7c124e- Tree
a1ecb9a- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
dd0635c
7 files changed+143 added−7 removed
modified:click/__init__.py+4 added-4 removed
22 unmodified lines23 command, group, argument, option, confirmation_option, \24 password_option, version_option, help_option25 26 # Types27-from .types import ParamType, File, Path, Choice, IntRange, STRING, INT, \28- FLOAT, BOOL, UUID, UNPROCESSED27+from .types import ParamType, File, Path, Choice, IntRange, Tuple, \28+ STRING, INT, FLOAT, BOOL, UUID, UNPROCESSED29 30 # Utilities31 from .utils import echo, get_binary_stream, get_text_stream, open_file, \32 format_filename, get_app_dir24 unmodified lines57 'argument', 'option', 'confirmation_option', 'password_option',58 'version_option', 'help_option',59 60 # 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',63 64 # Utilities65 'echo', 'get_binary_stream', 'get_text_stream', 'open_file',66 'format_filename', 'get_app_dir',19 unmodified linesmodified:click/core.py+26 added-3 removed
1164 unmodified lines1165 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 lines1181 """1182 param_type_name = 'parameter'1183 1184 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)1189+1190 self.type = convert_type(type, default)1191+1192+ # 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 = 11199+1200 self.required = required1201 self.callback = callback1202 self.nargs = nargs1203 self.multiple = False41 unmodified lines1245 return value1246 1247 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)1261+1262 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 linesmodified:click/types.py+39 added
18 unmodified lines19 * 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 = False24 25 #: the descriptive name of this type26 name = None27 39 unmodified lines67 """Helper method to fail with an invalid value message."""68 raise BadParameter(message, ctx=ctx, param=param)69 70 71+class CompositeParamType(ParamType):72+ is_composite = True73+74+ @property75+ def arity(self):76+ raise NotImplementedError()77+78+79 class FuncParamType(ParamType):80 81 def __init__(self, func):82 self.name = func.__name__330 unmodified lines413 414 return rv415 416 417+class 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.423+424+ For more information see :ref:`tuple-type`.425+426+ This can be selected by using a Python tuple literal as a type.427+428+ :param types: a list of types that should be used for the tuple items.429+ """430+431+ def __init__(self, types):432+ self.types = [convert_type(ty) for ty in types]433+434+ @property435+ def arity(self):436+ return len(self.types)437+438+ 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))443+444+445 def 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 linesmodified:docs/api.rst+2 added
127 unmodified lines128 .. autoclass:: Choice129 130 .. autoclass:: IntRange131 132+.. autoclass:: Tuple133+134 .. autoclass:: ParamType135 :members:136 137 Exceptions40 unmodified linesmodified:docs/options.rst+36 added
53 unmodified lines54 .. click:run::55 56 invoke(findme, args=['--pos', '2.0', '3.0'])57 58+.. _tuple-type:59+60+Tuples as Multi Value Options61+-----------------------------62+63+.. versionadded:: 4.064+65+As you can see that by using `nargs` set to a specific number each item in66+the resulting tuple is of the same type. This might not be what you want.67+Commonly you might want to use different types for different indexes in68+the tuple. For this you can directly specify a tuple as type:69+70+.. click:example::71+72+ @click.command()73+ @click.option('--item', type=(unicode, int))74+ def putitem(item):75+ click.echo('name=%s id=%d' % item)76+77+And on the command line:78+79+.. click:run::80+81+ invoke(putitem, args=['--item', 'peter', '1338'])82+83+By using a tuple literal as type, `nargs` gets automatically set to the84+length of the tuple and the :class:`click.Tuple` type is automatically85+used. The above example is thus equivalent to this:86+87+.. click:example::88+89+ @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)93+94 Multiple Options95 ----------------96 97 Similarly to ``nargs``, there is also the case of wanting to support a554 unmodified linesmodified:tests/test_arguments.py+21 added
32 unmodified lines33 'point=1/2',34 ]35 36 37+def 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+ ]44+45+ for opts in variations:46+ @click.command()47+ @click.argument('item', **opts)48+ def copy(item):49+ click.echo('name=%s id=%d' % item)50+51+ result = runner.invoke(copy, ['peter', '1'])52+ assert not result.exception53+ assert result.output.splitlines() == [54+ 'name=peter id=1',55+ ]56+57+58 def test_nargs_err(runner):59 @click.command()60 @click.argument('x')61 def copy(x):151 unmodified linesmodified:tests/test_options.py+15 added
44 unmodified lines45 else:46 assert False, 'Expected a type error because of an invalid option.'47 48 49+def 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)55+56+ 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+ ]62+63+64 def test_counting(runner):65 @click.command()66 @click.option('-v', count=True, help='Verbosity',67 type=click.IntRange(0, 3))226 unmodified lines