Created
May 9, 2013 01:33
-
-
Save bbengfort/5544936 to your computer and use it in GitHub Desktop.
A helper method for converting POST and JSON data to an expected Boolean object (Python 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
FALSE_STRINGS = ("0", "false", "[]", "{}", "()", "None", "no") | |
def boolean(obj): | |
""" | |
A helper method for converting POST and JSON data | |
to an expected Boolean object (Python bool). | |
We expect that the following are false: | |
0 | |
False | |
[] | |
{} | |
() | |
epsilon | |
None | |
Therefore case insensitive string representations | |
of them should also be false. If obj is a string, | |
we check for these representations, otherwise, | |
we simply revert to bool() | |
""" | |
if isinstance(obj, str) or isinstance(obj, unicode): | |
obj = obj.lower() # Case Insensitivity | |
if obj in FALSE_STRINGS: | |
return False | |
return bool(obj) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment