这是我写的版本。将其他几种解决方案合并为一个。
def to_bool(value):
"""
Converts 'something' to boolean. Raises exception if it gets a string it doesn't handle.
Case is ignored for strings. These string values are handled:
True: 'True', "1", "TRue", "yes", "y", "t"
False: "", "0", "faLse", "no", "n", "f"
Non-string values are passed to bool.
"""
if type(value) == type(''):
if value.lower() in ("yes", "y", "true", "t", "1"):
return True
if value.lower() in ("no", "n", "false", "f", "0", ""):
return False
raise Exception('Invalid value for boolean conversion: ' + value)
return bool(value)
如果它得到一个字符串,则它期望特定的值,否则引发Exception。如果没有得到字符串,只需让bool构造函数弄清楚即可。测试了以下情况:
test_cases = [
('true', True),
('t', True),
('yes', True),
('y', True),
('1', True),
('false', False),
('f', False),
('no', False),
('n', False),
('0', False),
('', False),
(1, True),
(0, False),
(1.0, True),
(0.0, False),
([], False),
({}, False),
((), False),
([1], True),
({1:2}, True),
((1,), True),
(None, False),
(object(), True),
]