Created
August 28, 2014 17:04
-
-
Save un33k/bad2b68a5687f80fe94c to your computer and use it in GitHub Desktop.
string to integer AND integer to string conversions for Django Options
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
def choices_txt_2_int(choices, text, default=0): | |
""" | |
Returns the integer `value` of a text from a choice tuple or `default`. | |
""" | |
value = default | |
if isinstance(text, str): | |
try: | |
value = next(v for v, k in choices if k.lower()==text.lower()) | |
except StopIteration: | |
pass | |
return value | |
def choices_int_2_txt(choices, integer, default='UNKNOWN'): | |
""" | |
Returns the text `value` of an integer from a choice tuple or `default`. | |
""" | |
try: | |
value = dict(choices)[integer] | |
except KeyError: | |
value = default | |
return value |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment