Skip to content

Instantly share code, notes, and snippets.

@hayajo
Last active November 7, 2017 07:50
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hayajo/288f6454d16ebbc95a8b2af9f5c361f5 to your computer and use it in GitHub Desktop.
Save hayajo/288f6454d16ebbc95a8b2af9f5c361f5 to your computer and use it in GitHub Desktop.
pythonで"True", "False"をboolに変換する
# -*- 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