Document type auto-conversion and test `set` and `frozenset` (#3808)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Rowlando13 · committed by GitHub · parents 00f257b, 394088a · Browse files · 6 files·+255 added−9 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
6 files+255 added−9 removed
- tests:+197 added−7 removed
- other:+58 added−2 removed
Provenance
- Commit
e5cb12b- Tree
d6b77d7- Author
Rowlando13 <67291205+Rowlando13@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent 1
00f257b- Parent 2
394088a
6 files changed+255 added−9 removed
modified:docs/arguments.md+4 added-2 removed
43 unmodified lines4445464748494849505152535455136 unmodified linesExpand all43 unmodified lines invoke(touch, args=['foo.txt'])```
An argument may be assigned a {ref}`parameter type <parameter-types>`.If no type is provided, the type of the default value is used. If nodefault value is provided, the type is assumed to be {data}`STRING`.If no type is provided, the type of the default value is used if it isrecognized, otherwise {data}`STRING` is used. If no default value isprovided, the type is assumed to be {data}`STRING`. See{ref}`type-inference` for the types that are recognized.
```{admonition} Note on Required Arguments:class: note
136 unmodified linesExpand allmodified:docs/parameter-types.md+52 added
151 unmodified lines152 * .. autoclass:: Path153 :noindex:154 ```155 156+(type-inference)=157+158+## How Click Infers a Type159+160+When `type` is not given, Click infers it from `default`. Only the defaults listed below161+are recognized. Every other default gives {data}`STRING`.162+163+| `default` | Inferred type |164+| ------------------------------------------------ | ----------------------------------------------- |165+| not given, or `None` | {data}`STRING` |166+| `"git"` | {data}`STRING` |167+| `5` | {data}`INT` |168+| `1.5` | {data}`FLOAT` |169+| `True` | {data}`BOOL` |170+| `[]` or `()` | {data}`STRING` |171+| `[1, 2]` or `(1, 2)` | {data}`INT` |172+| `[1.5, 2.5]` | {data}`FLOAT` |173+| `[1, "git"]` | {data}`INT` |174+| `[(1, "git")]` | {class}`Tuple` of ({data}`INT`, {data}`STRING`) |175+| `{1, 2}` or `frozenset({1, 2})` | {data}`STRING` |176+| `{"a": 1}` | {data}`STRING` |177+| {class}`uuid.UUID` or {class}`datetime.datetime` | {data}`STRING` |178+| `b"git"`, or any other object | {data}`STRING` |179+180+A `list` or `tuple` gives the type of its **first item only**, so `[1, "git"]` gives181+{data}`INT` and the second item is converted with it. A first item that is itself a182+`list` or `tuple` gives a {class}`Tuple`, which also sets `nargs`.183+184+A `set`, a `frozenset`, a `dict`, and a type Click ships but does not guess, such as185+{class}`uuid.UUID`, all land in the last group. Their default is converted with186+{data}`STRING`, so the command receives the `str()` form of the value.187+188+```{eval-rst}189+.. click:example::190+191+ @click.command()192+ @click.option('--count', default=5)193+ @click.option('--tag', default={'git'})194+ def show(count, tag):195+ click.echo(f"count is {type(count).__name__}, tag is {type(tag).__name__}")196+197+.. click:run::198+199+ invoke(show, args=[])200+```201+202+When `type` is given a callable Click does not recognize, that callable is called on the203+string coming from the command line, and a `ValueError` it raises is reported as a bad204+parameter. A container is rarely useful there, because calling it on a string splits the205+string: `set` turns `"git"` into `{"g", "i", "t"}`. Pass a {class}`ParamType` instead,206+as described in [](#how-to-implement-custom-types).207+208 ## How to Implement Custom Types209 210 To implement a custom type, you need to subclass the {class}`ParamType` class. For simple cases, passing a Python211 function that fails with a `ValueError` is also supported, though discouraged. Override the {meth}`~ParamType.convert`46 unmodified linesmodified:tests/test_defaults.py+4 added
180 unmodified lines181 ({"key": None}, "key", None),182 ({"key": 0}, "key", 0),183 ({"key": ""}, "key", ""),184 ({"key": False}, "key", False),185+ # Falsy containers are returned as-is too.186+ ({"key": set()}, "key", set()),187+ ({"key": frozenset()}, "key", frozenset()),188+ ({"key": {}}, "key", {}),189 ],190 )191 def test_lookup_default_returns_hides_sentinel(default_map, key, expected):192 """``lookup_default()`` should return ``None`` for missing keys, not :attr:`UNSET`.375 unmodified linesmodified:tests/test_options.py+87 added-7 removed
428 unmodified lines429 )430 assert not result.exception431 assert result.output == "foo|bar|baz\n"432 433+434+def test_envvar_container_type(runner):435+ """Env vars are plain strings, so a container type splits them character-wise.436+437+ Refs: https://github.com/pallets/click/issues/3036438+ """439+440 @click.command()441+ @click.option("--x", envvar="X", type=frozenset)442+ def cli(x):443+ assert isinstance(x, frozenset)444+ click.echo("".join(sorted(x)))445+446+ result = runner.invoke(cli, [], env={"X": "git"})447+ assert not result.exception448+ assert result.output == "git\n"449+450+ @click.command()451 @click.option("--arg", multiple=True, envvar="X")452 def cmd(arg):453 click.echo("|".join(arg))454 155 unmodified lines610 assert not result.exception611 assert "[default: b]" in result.output612 613 614+def test_show_default_container_defaults(runner):615+ """Container defaults are rendered through ``str()`` in the help output.616+617+ Refs: https://github.com/pallets/click/issues/3036618+ """619+620+ @click.command()621+ @click.option("--a", default=frozenset(["git"]), type=frozenset, show_default=True)622+ @click.option("--b", default={"a": 1}, type=dict, show_default=True)623+ @click.option("--c", default={"git"}, type=set, show_default=True)624+ def cli(a, b, c):625+ pass626+627+ result = runner.invoke(cli, ["--help"])628+ assert "[default: frozenset({'git'})]" in result.output629+ assert "[default: {'a': 1}]" in result.output630+ assert "[default: {'git'}]" in result.output631+632+633 def test_multiple_default_type():634 opt = click.Option(["-a"], multiple=True, default=(1, 2))635 assert opt.nargs == 1636 assert opt.multiple11 unmodified lines648 ctx = click.Context(click.Command("test"))649 assert opt.type_cast_value(ctx, opt.get_default(ctx)) == ((1, "a"),)650 651 652+@pytest.mark.parametrize(653+ "default",654+ [655+ set(),656+ {1, 2},657+ frozenset(),658+ frozenset(["git"]),659+ {},660+ {"a": 1},661+ ],662+)663+def test_type_from_default_container(default):664+ """Container defaults have no native Click type and fall back to STRING.665+666+ The documented "if no type is provided, the type of the default value is667+ used" rule does not apply to ``set``, ``frozenset`` or ``dict`` defaults.668+669+ Refs: https://github.com/pallets/click/issues/3036670+ """671+ opt = click.Option(["-a"], default=default)672+ assert opt.type is click.STRING673+674+675 def test_parse_multiple_default_composite_type(runner):676 @click.command()677 @click.option("-a", multiple=True, default=("a", "b"))678 @click.option("-b", multiple=True, default=[(1, "a")])804 unmodified lines1483 param = click.Option(["-c", "x"], flag_value=EngineType.OSS)1484 assert param.type is click.UNPROCESSED1485 param = click.Option(["-d", "x"], flag_value=frozenset())1486 assert param.type is click.UNPROCESSED1487+ param = click.Option(["-e", "x"], flag_value=set())1488+ assert param.type is click.UNPROCESSED1489+ param = click.Option(["-f", "x"], flag_value={})1490+ assert param.type is click.UNPROCESSED1491 1492 1493 @pytest.mark.parametrize(1494 ("opt_params", "args", "expected"),1103 unmodified lines2598 assert result.exit_code == 02599 assert result.output == repr(EngineType.PRO)2600 2601 2539-def test_custom_type_frozenset_flag_value(runner):2540- """Check that frozenset is correctly handled as a type, a flag value and a default.2602+@pytest.mark.parametrize(2603+ ("container_type", "flag_value", "default", "default_output", "flag_output"),2604+ [2605+ (set, set(), {"git"}, "{'git'}", "set()"),2606+ (2607+ frozenset,2608+ frozenset(),2609+ frozenset(["git"]),2610+ "frozenset({'git'})",2611+ "frozenset()",2612+ ),2613+ (dict, dict(), {"git": True}, "{'git': True}", "{}"),2614+ ],2615+)2616+def test_custom_type_container_flag_value(2617+ runner, container_type, flag_value, default, default_output, flag_output2618+):2619+ """Check that container types are correctly handled as a type, a flag value2620+ and a default.2621 2622 Reproduces https://github.com/pallets/click/issues/26102623 """2624 1 unmodified line2626 @click.option(2627 "--without-scm-ignore-files",2628 "scm_ignore_files",2629 is_flag=True,2550- type=frozenset,2551- flag_value=frozenset(),2552- default=frozenset(["git"]),2630+ type=container_type,2631+ flag_value=flag_value,2632+ default=default,2633 )2634 def rcli(scm_ignore_files):2635 click.echo(repr(scm_ignore_files), nl=False)2636 2637 result = runner.invoke(rcli)2558- assert result.stdout == "frozenset({'git'})"2638+ assert result.stdout == default_output2639 assert result.exit_code == 02640 2641 result = runner.invoke(rcli, ["--without-scm-ignore-files"])2562- assert result.stdout == "frozenset()"2642+ assert result.stdout == flag_output2643 assert result.exit_code == 02644 2645 2646 @pytest.mark.parametrize(985 unmodified linesmodified:tests/test_types.py+106 added
1+import datetime2 import os.path3 import pathlib4 import platform5 import subprocess6 import sys7 import tempfile8 import typing as t9+import uuid10 11 import pytest12 13 import click14 from click import FileError15+from click.types import convert_type16+from click.types import FuncParamType17 18 19 @pytest.mark.parametrize(20 ("type", "value", "expect"),312 unmodified lines333 334 doubling = DoublingType()335 assert doubling("21") == 42336 assert doubling(None) is None337+338+339+@pytest.mark.parametrize(340+ "default",341+ [342+ # Empty sequences fall back to STRING because ``_guess_type`` returns None.343+ [],344+ (),345+ # Container types are guessed from the default but are not natively346+ # supported, so they reach STRING through a different code path.347+ set(),348+ {1, 2},349+ frozenset(),350+ frozenset(["git"]),351+ {},352+ {"a": 1},353+ ],354+)355+def test_convert_type_from_container_default(default):356+ """Container defaults are not natively supported and fall back to STRING.357+358+ Refs: https://github.com/pallets/click/issues/3036359+ """360+ assert convert_type(None, default) is click.STRING361+362+363+@pytest.mark.parametrize(364+ ("container_type", "value", "expected"),365+ [366+ (set, "a,b,c", {"a", ",", "b", "c"}),367+ (frozenset, "abc", frozenset({"a", "b", "c"})),368+ ],369+)370+def test_explicit_container_type_splits_string(container_type, value, expected):371+ """An explicit ``set`` or ``frozenset`` type wraps the builtin in a372+ ``FuncParamType``, which splits CLI strings character-wise.373+374+ Refs: https://github.com/pallets/click/issues/3036375+ """376+ param_type = convert_type(container_type)377+ assert isinstance(param_type, FuncParamType)378+ assert param_type.convert(value, None, None) == expected379+380+381+def test_explicit_dict_type_rejects_string():382+ """An explicit ``dict`` type cannot convert a plain CLI string at all.383+384+ Refs: https://github.com/pallets/click/issues/3036385+ """386+ param_type = convert_type(dict)387+ assert isinstance(param_type, FuncParamType)388+ with pytest.raises(click.BadParameter):389+ param_type.convert("abc", None, None)390+391+392+@pytest.mark.parametrize(393+ ("default", "expected"),394+ [395+ # Recognized scalars.396+ (None, click.STRING),397+ ("git", click.STRING),398+ (5, click.INT),399+ (1.5, click.FLOAT),400+ (True, click.BOOL),401+ # An empty sequence gives no item to read.402+ ([], click.STRING),403+ ((), click.STRING),404+ # A sequence gives the type of its first item only.405+ ([1, 2], click.INT),406+ ((1, 2), click.INT),407+ ([1.5, 2.5], click.FLOAT),408+ ([1, "git"], click.INT),409+ # Everything else falls back to STRING, including types Click ships.410+ ({1, 2}, click.STRING),411+ (frozenset({1, 2}), click.STRING),412+ ({"a": 1}, click.STRING),413+ (uuid.UUID(int=0), click.STRING),414+ (datetime.datetime(2026, 1, 1), click.STRING),415+ (b"git", click.STRING),416+ (object(), click.STRING),417+ ],418+)419+def test_type_inferred_from_default(default, expected):420+ """Every row of the type-inference table in ``docs/parameter-types.md``.421+422+ Keep the two in step: a change here is a change to documented behavior.423+424+ Refs: https://github.com/pallets/click/issues/3036425+ """426+ assert convert_type(None, default) is expected427+428+429+def test_type_inferred_from_nested_sequence_default():430+ """A sequence of sequences gives a composite ``Tuple`` of the inner types.431+432+ This is the one table row that is not a singleton ``ParamType``.433+434+ Refs: https://github.com/pallets/click/issues/3036435+ """436+ param_type = convert_type(None, [(1, "git")])437+ assert isinstance(param_type, click.Tuple)438+ assert param_type.types == [click.INT, click.STRING]modified:CHANGES.md+2 added
4 unmodified lines5 - Fix `copy.deepcopy()` and `pickle` on a `Parameter`, `Option` or `Command`. {pr}`3805`6 - A `KeyboardInterrupt` arriving while `Command.main()` reports an abort or an error,7 or while it exits, no longer escapes as an unhandled traceback. The command still8 exits with the intended code; only the message may be lost. {issue}`3802`9+- Document which types are inferred from `default`, and what an unrecognized10+ `type` callable does to a command-line value. {issue}`3036` {pr}`3808`11 12 ## Version 8.5.013 14 Released 2026-08-241655 unmodified lines