I'm making a webapp that does some data processing, so I frequently find myself parsing strings (from an URL or a text file) into Python values.
I use a function that is "kind of" a safer version of eval (except that if it can't read the string, it stays a string):
def str_to_value(string):
for atom in (True, False, None):
if str(atom) == string:
return atom
else:
try:
return int(string)
except ValueError:
try:
return float(string)
except ValueError:
return string
... however, this seems very ugly to me. Is there a cleaner way of doing this? I found an old discussion os something like this, but I'm wondering if there isn't a quick and simple way (like a library function I don't know of, or a clever one-liner?).
ast.literal_eval()