Skip to content

Instantly share code, notes, and snippets.

@bbengfort
Created May 9, 2013 01:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bbengfort/5544936 to your computer and use it in GitHub Desktop.
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).
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