If 'bool_from_string' provided a boolean just return it

Typically the pattern of the following happens:

>>> s = dict()
>>> v = s.get("blah", True)
>>> v = strutils.bool_from_string(v)

In this case we can avoid converting the value of 'v' to a bool
if it was already a boolean (and if it wasn't then the rest of
the code can be ran to attempt to convert it to one). This avoids
needlessly converting things from bool -> string -> bool which
is not really needed in this case.

Change-Id: Id7397e91e754ff2c63b3f112e95aedf82cd31717
This commit is contained in:
Joshua Harlow 2015-09-16 08:22:36 -07:00
parent a0d56eaeae
commit b9739be699
2 changed files with 8 additions and 0 deletions

View File

@ -119,6 +119,8 @@ def bool_from_string(subject, strict=False, default=False):
ValueError which is useful when parsing values passed in from an API call.
Strings yielding False are 'f', 'false', 'off', 'n', 'no', or '0'.
"""
if isinstance(subject, bool):
return subject
if not isinstance(subject, six.string_types):
subject = six.text_type(subject)

View File

@ -30,6 +30,12 @@ load_tests = testscenarios.load_tests_apply_scenarios
class StrUtilsTest(test_base.BaseTestCase):
@mock.patch("six.text_type")
def test_bool_bool_from_string_no_text(self, mock_text):
self.assertTrue(strutils.bool_from_string(True))
self.assertFalse(strutils.bool_from_string(False))
self.assertEqual(0, mock_text.call_count)
def test_bool_bool_from_string(self):
self.assertTrue(strutils.bool_from_string(True))
self.assertFalse(strutils.bool_from_string(False))