Skip to content
Myr

Test frozen types; Documents type conversion

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

Refs #3036

authored by Kevin Deldycke · committed by Kevin Deldycke · parent 00f257b · 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

6 files+255 added−9 removed

modified:docs/arguments.md+4 added-2 removed
modified:docs/parameter-types.md+52 added
151 unmodified lines
152* .. autoclass:: Path153 :noindex:154```155156(type-inference)=157158## How Click Infers a Type159160When `type` is not given, Click infers it from `default`. Only the defaults listed below161are recognized. Every other default gives {data}`STRING`.162163| `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` |179180A `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`.183184A `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.187188```{eval-rst}189.. click:example::190191 @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__}")196197.. click:run::198199 invoke(show, args=[])200```201202When `type` is given a callable Click does not recognize, that callable is called on the203string coming from the command line, and a `ValueError` it raises is reported as a bad204parameter. A container is rarely useful there, because calling it on a string splits the205string: `set` turns `"git"` into `{"g", "i", "t"}`. Pass a {class}`ParamType` instead,206as described in [](#how-to-implement-custom-types).207208## How to Implement Custom Types209210To implement a custom type, you need to subclass the {class}`ParamType` class. For simple cases, passing a Python211function that fails with a `ValueError` is also supported, though discouraged. Override the {meth}`~ParamType.convert`
46 unmodified lines
modified:tests/test_defaults.py+4 added
180 unmodified lines
181 ({"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)191def test_lookup_default_returns_hides_sentinel(default_map, key, expected):192 """``lookup_default()`` should return ``None`` for missing keys, not :attr:`UNSET`.
375 unmodified lines
modified:tests/test_options.py+87 added-7 removed
428 unmodified lines
429 )430 assert not result.exception431 assert result.output == "foo|bar|baz\n"432433434def test_envvar_container_type(runner):435 """Env vars are plain strings, so a container type splits them character-wise.436437 Refs: https://github.com/pallets/click/issues/3036438 """439440 @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)))445446 result = runner.invoke(cli, [], env={"X": "git"})447 assert not result.exception448 assert result.output == "git\n"449450 @click.command()451 @click.option("--arg", multiple=True, envvar="X")452 def cmd(arg):453 click.echo("|".join(arg))454
155 unmodified lines
610 assert not result.exception611 assert "[default: b]" in result.output612613614def test_show_default_container_defaults(runner):615 """Container defaults are rendered through ``str()`` in the help output.616617 Refs: https://github.com/pallets/click/issues/3036618 """619620 @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 pass626627 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.output631632633def test_multiple_default_type():634 opt = click.Option(["-a"], multiple=True, default=(1, 2))635 assert opt.nargs == 1636 assert opt.multiple
11 unmodified lines
648 ctx = click.Context(click.Command("test"))649 assert opt.type_cast_value(ctx, opt.get_default(ctx)) == ((1, "a"),)650651652@pytest.mark.parametrize(653 "default",654 [655 set(),656 {1, 2},657 frozenset(),658 frozenset(["git"]),659 {},660 {"a": 1},661 ],662)663def test_type_from_default_container(default):664 """Container defaults have no native Click type and fall back to STRING.665666 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.668669 Refs: https://github.com/pallets/click/issues/3036670 """671 opt = click.Option(["-a"], default=default)672 assert opt.type is click.STRING673674675def 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 lines
1483 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.UNPROCESSED149114921493@pytest.mark.parametrize(1494 ("opt_params", "args", "expected"),
1103 unmodified lines
2598 assert result.exit_code == 02599 assert result.output == repr(EngineType.PRO)260026012539def 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)2616def 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.26212622 Reproduces https://github.com/pallets/click/issues/26102623 """2624
1 unmodified line
2626 @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)26362637 result = runner.invoke(rcli)2558 assert result.stdout == "frozenset({'git'})"2638 assert result.stdout == default_output2639 assert result.exit_code == 026402641 result = runner.invoke(rcli, ["--without-scm-ignore-files"])2562 assert result.stdout == "frozenset()"2642 assert result.stdout == flag_output2643 assert result.exit_code == 0264426452646@pytest.mark.parametrize(
985 unmodified lines
modified:tests/test_types.py+106 added
1import datetime2import os.path3import pathlib4import platform5import subprocess6import sys7import tempfile8import typing as t9import uuid1011import pytest1213import click14from click import FileError15from click.types import convert_type16from click.types import FuncParamType171819@pytest.mark.parametrize(20 ("type", "value", "expect"),
312 unmodified lines
333334 doubling = DoublingType()335 assert doubling("21") == 42336 assert doubling(None) is None337338339@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)355def test_convert_type_from_container_default(default):356 """Container defaults are not natively supported and fall back to STRING.357358 Refs: https://github.com/pallets/click/issues/3036359 """360 assert convert_type(None, default) is click.STRING361362363@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)370def 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.373374 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) == expected379380381def test_explicit_dict_type_rejects_string():382 """An explicit ``dict`` type cannot convert a plain CLI string at all.383384 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)390391392@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)419def test_type_inferred_from_default(default, expected):420 """Every row of the type-inference table in ``docs/parameter-types.md``.421422 Keep the two in step: a change here is a change to documented behavior.423424 Refs: https://github.com/pallets/click/issues/3036425 """426 assert convert_type(None, default) is expected427428429def test_type_inferred_from_nested_sequence_default():430 """A sequence of sequences gives a composite ``Tuple`` of the inner types.431432 This is the one table row that is not a singleton ``ParamType``.433434 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 lines
5- 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`1112## Version 8.5.01314Released 2026-08-24
1655 unmodified lines