Skip to content

Commit 23a7d22

Browse files
authored
Merge pull request #1253 from python-cmd2/1252-str-to-bool
Enhance str_to_bool() to accept other types
2 parents e95af81 + 860403e commit 23a7d22

File tree

3 files changed

+43
-23
lines changed

3 files changed

+43
-23
lines changed

cmd2/utils.py

+14-7
Original file line numberDiff line numberDiff line change
@@ -89,19 +89,26 @@ def strip_quotes(arg: str) -> str:
8989
return arg
9090

9191

92-
def str_to_bool(val: str) -> bool:
93-
"""Converts a string to a boolean based on its value.
92+
def to_bool(val: Any) -> bool:
93+
"""Converts anything to a boolean based on its value.
9494
95-
:param val: string being converted
96-
:return: boolean value expressed in the string
95+
Strings like "True", "true", "False", and "false" return True, True, False, and False
96+
respectively. All other values are converted using bool()
97+
98+
:param val: value being converted
99+
:return: boolean value expressed in the passed in value
97100
:raises: ValueError if the string does not contain a value corresponding to a boolean value
98101
"""
99102
if isinstance(val, str):
100103
if val.capitalize() == str(True):
101104
return True
102105
elif val.capitalize() == str(False):
103106
return False
104-
raise ValueError("must be True or False (case-insensitive)")
107+
raise ValueError("must be True or False (case-insensitive)")
108+
elif isinstance(val, bool):
109+
return val
110+
else:
111+
return bool(val)
105112

106113

107114
class Settable:
@@ -126,7 +133,7 @@ def __init__(
126133
:param name: name of the instance attribute being made settable
127134
:param val_type: callable used to cast the string value from the command line into its proper type and
128135
even validate its value. Setting this to bool provides tab completion for true/false and
129-
validation using str_to_bool(). The val_type function should raise an exception if it fails.
136+
validation using to_bool(). The val_type function should raise an exception if it fails.
130137
This exception will be caught and printed by Cmd.do_set().
131138
:param description: string describing this setting
132139
:param settable_object: object to which the instance attribute belongs (e.g. self)
@@ -153,7 +160,7 @@ def get_bool_choices(_) -> List[str]: # type: ignore[no-untyped-def]
153160
"""Used to tab complete lowercase boolean values"""
154161
return ['true', 'false']
155162

156-
val_type = str_to_bool
163+
val_type = to_bool
157164
choices_provider = cast(ChoicesProviderFunc, get_bool_choices)
158165

159166
self.name = name

docs/api/utils.rst

+1-1
Original file line numberDiff line numberDiff line change
@@ -88,7 +88,7 @@ Text Alignment
8888
Miscellaneous
8989
-------------
9090

91-
.. autofunction:: cmd2.utils.str_to_bool
91+
.. autofunction:: cmd2.utils.to_bool
9292

9393
.. autofunction:: cmd2.utils.categorize
9494

tests/test_utils.py

+28-15
Original file line numberDiff line numberDiff line change
@@ -824,28 +824,41 @@ def test_align_right_wide_fill_needs_padding():
824824
assert aligned == fill_char + ' ' + text
825825

826826

827-
def test_str_to_bool_true():
828-
assert cu.str_to_bool('true')
829-
assert cu.str_to_bool('True')
830-
assert cu.str_to_bool('TRUE')
831-
assert cu.str_to_bool('tRuE')
827+
def test_to_bool_str_true():
828+
assert cu.to_bool('true')
829+
assert cu.to_bool('True')
830+
assert cu.to_bool('TRUE')
831+
assert cu.to_bool('tRuE')
832832

833833

834-
def test_str_to_bool_false():
835-
assert not cu.str_to_bool('false')
836-
assert not cu.str_to_bool('False')
837-
assert not cu.str_to_bool('FALSE')
838-
assert not cu.str_to_bool('fAlSe')
834+
def test_to_bool_str_false():
835+
assert not cu.to_bool('false')
836+
assert not cu.to_bool('False')
837+
assert not cu.to_bool('FALSE')
838+
assert not cu.to_bool('fAlSe')
839839

840840

841-
def test_str_to_bool_invalid():
841+
def test_to_bool_str_invalid():
842842
with pytest.raises(ValueError):
843-
cu.str_to_bool('other')
843+
cu.to_bool('other')
844844

845845

846-
def test_str_to_bool_bad_input():
847-
with pytest.raises(ValueError):
848-
cu.str_to_bool(1)
846+
def test_to_bool_bool():
847+
assert cu.to_bool(True)
848+
assert not cu.to_bool(False)
849+
850+
851+
def test_to_bool_int():
852+
assert cu.to_bool(1)
853+
assert cu.to_bool(-1)
854+
assert not cu.to_bool(0)
855+
856+
857+
def test_to_bool_float():
858+
assert cu.to_bool(2.35)
859+
assert cu.to_bool(0.25)
860+
assert cu.to_bool(-3.1415)
861+
assert not cu.to_bool(0)
849862

850863

851864
def test_find_editor_specified():

0 commit comments

Comments
 (0)