Skip to content

Commit

Permalink
Merge pull request #1253 from python-cmd2/1252-str-to-bool
Browse files Browse the repository at this point in the history
Enhance str_to_bool() to accept other types
  • Loading branch information
kotfu committed Nov 7, 2022
2 parents e95af81 + 860403e commit 23a7d22
Show file tree
Hide file tree
Showing 3 changed files with 43 additions and 23 deletions.
21 changes: 14 additions & 7 deletions cmd2/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -89,19 +89,26 @@ def strip_quotes(arg: str) -> str:
return arg


def str_to_bool(val: str) -> bool:
"""Converts a string to a boolean based on its value.
def to_bool(val: Any) -> bool:
"""Converts anything to a boolean based on its value.
:param val: string being converted
:return: boolean value expressed in the string
Strings like "True", "true", "False", and "false" return True, True, False, and False
respectively. All other values are converted using bool()
:param val: value being converted
:return: boolean value expressed in the passed in value
:raises: ValueError if the string does not contain a value corresponding to a boolean value
"""
if isinstance(val, str):
if val.capitalize() == str(True):
return True
elif val.capitalize() == str(False):
return False
raise ValueError("must be True or False (case-insensitive)")
raise ValueError("must be True or False (case-insensitive)")
elif isinstance(val, bool):
return val
else:
return bool(val)


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

val_type = str_to_bool
val_type = to_bool
choices_provider = cast(ChoicesProviderFunc, get_bool_choices)

self.name = name
Expand Down
2 changes: 1 addition & 1 deletion docs/api/utils.rst
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ Text Alignment
Miscellaneous
-------------

.. autofunction:: cmd2.utils.str_to_bool
.. autofunction:: cmd2.utils.to_bool

.. autofunction:: cmd2.utils.categorize

Expand Down
43 changes: 28 additions & 15 deletions tests/test_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -824,28 +824,41 @@ def test_align_right_wide_fill_needs_padding():
assert aligned == fill_char + ' ' + text


def test_str_to_bool_true():
assert cu.str_to_bool('true')
assert cu.str_to_bool('True')
assert cu.str_to_bool('TRUE')
assert cu.str_to_bool('tRuE')
def test_to_bool_str_true():
assert cu.to_bool('true')
assert cu.to_bool('True')
assert cu.to_bool('TRUE')
assert cu.to_bool('tRuE')


def test_str_to_bool_false():
assert not cu.str_to_bool('false')
assert not cu.str_to_bool('False')
assert not cu.str_to_bool('FALSE')
assert not cu.str_to_bool('fAlSe')
def test_to_bool_str_false():
assert not cu.to_bool('false')
assert not cu.to_bool('False')
assert not cu.to_bool('FALSE')
assert not cu.to_bool('fAlSe')


def test_str_to_bool_invalid():
def test_to_bool_str_invalid():
with pytest.raises(ValueError):
cu.str_to_bool('other')
cu.to_bool('other')


def test_str_to_bool_bad_input():
with pytest.raises(ValueError):
cu.str_to_bool(1)
def test_to_bool_bool():
assert cu.to_bool(True)
assert not cu.to_bool(False)


def test_to_bool_int():
assert cu.to_bool(1)
assert cu.to_bool(-1)
assert not cu.to_bool(0)


def test_to_bool_float():
assert cu.to_bool(2.35)
assert cu.to_bool(0.25)
assert cu.to_bool(-3.1415)
assert not cu.to_bool(0)


def test_find_editor_specified():
Expand Down

0 comments on commit 23a7d22

Please sign in to comment.