Last active
November 7, 2017 07:50
-
-
Save hayajo/288f6454d16ebbc95a8b2af9f5c361f5 to your computer and use it in GitHub Desktop.
pythonで"True", "False"をboolに変換する
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf-8 -*- | |
from ast import literal_eval | |
def parse_bool(value): | |
"""test | |
>>> parse_bool("True") | |
True | |
>>> parse_bool("False") | |
False | |
>>> parse_bool(True) | |
True | |
>>> parse_bool(False) | |
False | |
>>> parse_bool("1") | |
Traceback (most recent call last): | |
... | |
ValueError: malformed value | |
>>> parse_bool("true") | |
Traceback (most recent call last): | |
... | |
ValueError: malformed string | |
>>> parse_bool("false") | |
Traceback (most recent call last): | |
... | |
ValueError: malformed string | |
>>> parse_bool("'hgoehoge'") | |
Traceback (most recent call last): | |
... | |
ValueError: malformed value | |
>>> parse_bool("") | |
Traceback (most recent call last): | |
... | |
SyntaxError: unexpected EOF while parsing | |
>>> parse_bool("hogehoge") | |
Traceback (most recent call last): | |
... | |
ValueError: malformed string | |
""" | |
if isinstance(value, str): | |
value = literal_eval(value) | |
if not isinstance(value, bool): | |
raise ValueError('malformed value') | |
return value | |
if __name__ == "__main__": | |
import doctest | |
doctest.testmod() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment