From 1771269308e56df46effe229ff56693b2b98a506 Mon Sep 17 00:00:00 2001 From: Leo Singer Date: Sun, 22 Dec 2024 08:27:35 -0500 Subject: [PATCH 1/2] Only try to set flag_value if is_flag is true This statement: flag_value = not self.default requires the class to have a working `__bool__` method. However, there are some classes that explicitly disable this method: - [`numpy.ndarray`](https://numpy.org/doc/stable/reference/arrays.ndarray.html) raises `ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()` - [`astropy.units.Quantity`](https://docs.astropy.org/en/stable/api/astropy.units.Quantity.html) raises `ValueError: Quantity truthiness is ambiguous, especially for logarithmic units and temperatures. Use explicit comparisons.` Move this statement so that it is only executed if `is_flag` is true. --- src/click/core.py | 5 ++--- tests/test_info_dict.py | 2 +- 2 files changed, 3 insertions(+), 4 deletions(-) diff --git a/src/click/core.py b/src/click/core.py index 1c1a46714..e783729c7 100644 --- a/src/click/core.py +++ b/src/click/core.py @@ -2597,11 +2597,10 @@ def __init__( else: self.default = False - if flag_value is None: - flag_value = not self.default - self.type: types.ParamType if is_flag and type is None: + if flag_value is None: + flag_value = not self.default # Re-guess the type from the flag value instead of the # default. self.type = types.convert_type(None, flag_value) diff --git a/tests/test_info_dict.py b/tests/test_info_dict.py index 79d39ee51..11b670311 100644 --- a/tests/test_info_dict.py +++ b/tests/test_info_dict.py @@ -58,7 +58,7 @@ "help": None, "prompt": None, "is_flag": False, - "flag_value": False, + "flag_value": None, "count": False, "hidden": False, }, From b4da7684a129d2bb4004b26189419b477ca2bba0 Mon Sep 17 00:00:00 2001 From: Andreas Backx Date: Sun, 22 Dec 2024 21:23:31 +0100 Subject: [PATCH 2/2] Added changelog. --- CHANGES.rst | 3 +++ 1 file changed, 3 insertions(+) diff --git a/CHANGES.rst b/CHANGES.rst index 1a38be8cf..bebfef238 100644 --- a/CHANGES.rst +++ b/CHANGES.rst @@ -91,6 +91,9 @@ Unreleased - Add a ``catch_exceptions`` parameter to :class:`CliRunner`. If ``catch_exceptions`` is not passed to :meth:`CliRunner.invoke`, the value from :class:`CliRunner`. :issue:`2817` :pr:`2818` +- ``Option.flag_value`` will no longer have a default value set based on + ``Option.default`` if ``Option.is_flag`` is ``False``. This results in + ``Option.default`` not needing to implement `__bool__`. :pr:`2829` Version 8.1.8 -------------