From e0033315510510acdba14e880a361ccca091fb4b Mon Sep 17 00:00:00 2001 From: Matthew Martin Date: Wed, 5 Jan 2022 21:16:43 -0600 Subject: [PATCH] fix ParamType.to_info_dict() with no name --- CHANGES.rst | 2 ++ docs/shell-completion.rst | 2 ++ src/click/types.py | 9 ++++++++- tests/test_info_dict.py | 7 +++++++ 4 files changed, 19 insertions(+), 1 deletion(-) diff --git a/CHANGES.rst b/CHANGES.rst index 0a9661a3f..91b9ec1c4 100644 --- a/CHANGES.rst +++ b/CHANGES.rst @@ -48,6 +48,8 @@ Version 8.1.0 - A ``Group`` with ``invoke_without_command=True`` and ``chain=False`` will invoke its result callback with the group function's return value. :issue:`2124` +- ``to_info_dict`` will not fail if a ``ParamType`` doesn't define a + ``name``. :issue:`2168` Version 8.0.4 diff --git a/docs/shell-completion.rst b/docs/shell-completion.rst index 699d25d9b..ebf73c323 100644 --- a/docs/shell-completion.rst +++ b/docs/shell-completion.rst @@ -132,6 +132,8 @@ with the incomplete value. .. code-block:: python class EnvVarType(ParamType): + name = "envvar" + def shell_complete(self, ctx, param, incomplete): return [ CompletionItem(name) diff --git a/src/click/types.py b/src/click/types.py index aab0656ed..3a78a3a1b 100644 --- a/src/click/types.py +++ b/src/click/types.py @@ -63,7 +63,14 @@ def to_info_dict(self) -> t.Dict[str, t.Any]: # The class name without the "ParamType" suffix. param_type = type(self).__name__.partition("ParamType")[0] param_type = param_type.partition("ParameterType")[0] - return {"param_type": param_type, "name": self.name} + + # Custom subclasses might not remember to set a name. + if hasattr(self, "name"): + name = self.name + else: + name = param_type + + return {"param_type": param_type, "name": name} def __call__( self, diff --git a/tests/test_info_dict.py b/tests/test_info_dict.py index b58ad6efb..79d39ee51 100644 --- a/tests/test_info_dict.py +++ b/tests/test_info_dict.py @@ -266,3 +266,10 @@ def test_context(): "ignore_unknown_options": False, "auto_envvar_prefix": None, } + + +def test_paramtype_no_name(): + class TestType(click.ParamType): + pass + + assert TestType().to_info_dict()["name"] == "TestType"