Skip to content

Commit

Permalink
Only try to set flag_value if is_flag is true
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
lpsinger committed Dec 22, 2024
1 parent 88328fc commit 1771269
Show file tree
Hide file tree
Showing 2 changed files with 3 additions and 4 deletions.
5 changes: 2 additions & 3 deletions src/click/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
2 changes: 1 addition & 1 deletion tests/test_info_dict.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@
"help": None,
"prompt": None,
"is_flag": False,
"flag_value": False,
"flag_value": None,
"count": False,
"hidden": False,
},
Expand Down

0 comments on commit 1771269

Please sign in to comment.