strutils bool_from_string, allow specified default
In certain cases, we may want to return true by default, e.g see the discussion in https://review.openstack.org/#/c/65725/, so provide a "default" argument which can be used to override the existing default False response. Change-Id: I6c86b03125f263cf4843b4cf1addf9e9812f53a8
This commit is contained in:
parent
8710dbacfd
commit
e53fe852c4
@ -58,12 +58,12 @@ def int_from_bool_as_string(subject):
|
|||||||
return bool_from_string(subject) and 1 or 0
|
return bool_from_string(subject) and 1 or 0
|
||||||
|
|
||||||
|
|
||||||
def bool_from_string(subject, strict=False):
|
def bool_from_string(subject, strict=False, default=False):
|
||||||
"""Interpret a string as a boolean.
|
"""Interpret a string as a boolean.
|
||||||
|
|
||||||
A case-insensitive match is performed such that strings matching 't',
|
A case-insensitive match is performed such that strings matching 't',
|
||||||
'true', 'on', 'y', 'yes', or '1' are considered True and, when
|
'true', 'on', 'y', 'yes', or '1' are considered True and, when
|
||||||
`strict=False`, anything else is considered False.
|
`strict=False`, anything else returns the value specified by 'default'.
|
||||||
|
|
||||||
Useful for JSON-decoded stuff and config file parsing.
|
Useful for JSON-decoded stuff and config file parsing.
|
||||||
|
|
||||||
@ -88,7 +88,7 @@ def bool_from_string(subject, strict=False):
|
|||||||
'acceptable': acceptable}
|
'acceptable': acceptable}
|
||||||
raise ValueError(msg)
|
raise ValueError(msg)
|
||||||
else:
|
else:
|
||||||
return False
|
return default
|
||||||
|
|
||||||
|
|
||||||
def safe_decode(text, incoming=None, errors='strict'):
|
def safe_decode(text, incoming=None, errors='strict'):
|
||||||
|
@ -28,6 +28,10 @@ class StrUtilsTest(test.BaseTestCase):
|
|||||||
self.assertTrue(strutils.bool_from_string(True))
|
self.assertTrue(strutils.bool_from_string(True))
|
||||||
self.assertFalse(strutils.bool_from_string(False))
|
self.assertFalse(strutils.bool_from_string(False))
|
||||||
|
|
||||||
|
def test_bool_bool_from_string_default(self):
|
||||||
|
self.assertTrue(strutils.bool_from_string('', default=True))
|
||||||
|
self.assertFalse(strutils.bool_from_string('wibble', default=False))
|
||||||
|
|
||||||
def _test_bool_from_string(self, c):
|
def _test_bool_from_string(self, c):
|
||||||
self.assertTrue(strutils.bool_from_string(c('true')))
|
self.assertTrue(strutils.bool_from_string(c('true')))
|
||||||
self.assertTrue(strutils.bool_from_string(c('TRUE')))
|
self.assertTrue(strutils.bool_from_string(c('TRUE')))
|
||||||
|
Loading…
Reference in New Issue
Block a user