30 000 % speed improvement
String formatting
Cutting off the internet
Here are different way to transform values from a config
file to a boolean
Which is your favourite ?
devpi
install z3c.appconfig
>>>
from z3c.appconfig.utils import asBool
>>>
asBool("true")
True
>>>
asBool(1)
True
>>>
asBool(-1)
True
>>>
asBool("no")
False
>>>
asBool("yes")
True
>>>
asBool("Yes")
True
>>>
asBool("YES")
True
>>>
asBool("NO")
False
>>>
asBool("off")
False
>>>
asBool("on")
True
>>>
asBool('Lorem')
Traceback
(most recent call last):
File "<stdin>", line 1, in <module>
File
"/home/nlaurance/PycharmProjects/dev_venv/local/lib/python2.7/site-packages/z3c/appconfig/utils.py",
line 18, in asBool
raise ValueError("Invalid boolean: %s" % value)
ValueError:
Invalid boolean: lorem
>>>
asBool(456)
True
>>>
asBool(0)
False
devpi
install distutils
>>>
from distutils.util import strtobool
>>>
strtobool('true')
1
>>>
strtobool('False')
0
>>>
strtobool('off')
0
>>>
strtobool('on')
1
>>>
strtobool('y')
1
>>>
strtobool('n')
0
>>>
strtobool('lorem')
Traceback
(most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/distutils/util.py", line 325, in strtobool
raise ValueError, "invalid truth value %r" % (val,)
ValueError:
invalid truth value 'lorem'
>>>
strtobool('1')
1
>>>
strtobool(456)
Traceback
(most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/distutils/util.py", line 319, in strtobool
val = string.lower(val)
File "/usr/lib/python2.7/string.py", line 226, in lower
return s.lower()
AttributeError:
'int' object has no attribute 'lower'
Roll
your own
>>>
def asbool(value):
...
return str(value).lower() in ('true', 't', 'on', 'yes', 'y', '1', '1.0')
...
>>>
asbool('f')
False
>>>
asbool('YES')
True
>>>
asbool(True)
True
>>>
asbool(False)
False
>>>
asbool(0)
False
>>>
asbool(1)
True
>>>
asbool(-1)
False
>>>
asbool('On')
True
No comments:
Post a Comment