Skip to content

Commit 0fde422

Browse files
authored
Merge pull request #2807 from nipy/oesteban-patch-2
[ENH] Improve ``str2bool`` + doctests
2 parents b7f5cdd + 787f4fd commit 0fde422

File tree

1 file changed

+50
-8
lines changed

1 file changed

+50
-8
lines changed

nipype/utils/misc.py

Lines changed: 50 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
"""
66
from __future__ import (print_function, unicode_literals, division,
77
absolute_import)
8-
from builtins import next, str
8+
from builtins import next, bytes, str
99

1010
import os
1111
import sys
@@ -192,15 +192,57 @@ def package_check(pkg_name,
192192

193193

194194
def str2bool(v):
195+
"""
196+
Convert strings (and bytearrays) to boolean values
197+
198+
>>> all([str2bool(v) for v in (True, "yes", "true",
199+
... "y", "t", "Yes", "True", "1", "on", "On")])
200+
True
201+
>>> all([str2bool(v.encode('utf-8'))
202+
... for v in ("yes", "true", "y", "t", "1", "Yes", "on", "On")])
203+
True
204+
>>> any([str2bool(v) for v in (False, "no", "false", "n", "f",
205+
... "False", "0", "off", "Off")])
206+
False
207+
>>> any([str2bool(v.encode('utf-8'))
208+
... for v in ("no", "false", "n", "f", "0", "off", "Off")])
209+
False
210+
>>> str2bool(None) # doctest: +ELLIPSIS
211+
Traceback (most recent call last):
212+
...
213+
ValueError: ...
214+
>>> str2bool('/some/path') # doctest: +ELLIPSIS
215+
Traceback (most recent call last):
216+
...
217+
ValueError: ...
218+
>>> str2bool('Agg') # doctest: +ELLIPSIS
219+
Traceback (most recent call last):
220+
...
221+
ValueError: ...
222+
>>> str2bool('INFO') # doctest: +ELLIPSIS
223+
Traceback (most recent call last):
224+
...
225+
ValueError: ...
226+
>>> str2bool('/some/bytes/path'.encode('utf-8')) # doctest: +ELLIPSIS
227+
Traceback (most recent call last):
228+
...
229+
ValueError: ...
230+
231+
"""
195232
if isinstance(v, bool):
196233
return v
197-
lower = v.lower()
198-
if lower in ("yes", "true", "t", "1"):
199-
return True
200-
elif lower in ("no", "false", "n", "f", "0"):
201-
return False
202-
else:
203-
raise ValueError("%s cannot be converted to bool" % v)
234+
235+
if isinstance(v, bytes):
236+
v = v.decode('utf-8')
237+
238+
if isinstance(v, str):
239+
lower = v.lower()
240+
if lower in ("yes", "true", "y", "t", "1", "on"):
241+
return True
242+
elif lower in ("no", "false", "n", "f", "0", "off"):
243+
return False
244+
245+
raise ValueError("%r cannot be converted to bool" % v)
204246

205247

206248
def flatten(S):

0 commit comments

Comments
 (0)