I\'m trying to (slightly) improve a script that does a quick-and-hacky parse of some config files.
Upon recognising \"an item\" read from the file, I need to try to conv
ast.literal_eval() handles all simple Python literals, and most compound literals.
... And sure enough, I just found the answer after I posted.
Even better than what I was looking for is ast.literal_eval
: ast — Abstract Syntax Trees
It can evaluate any Python expression consisting solely of literals, which makes it safe. It also means I can recognise items from the config file that are potentially numbers or strings without having attempt multiple conversions, falling back to the next conversion on a ValueError
exception. I don't even have to figure out what type the item is.
It's even way more flexible than I need, which could be a problem if I cared about making sure the item was only a number or a string, but I don't:
>>> ast.literal_eval('{"foo": [23.8, 170, (1, 2, 3)]}')
{'foo': [23.8, 170, (1, 2, 3)]}