I've got a problem with the utilisation of ast.literal_eval(). In the example below, I only want to convert the string (myText) to dictionnary. But ast.literal_eval() try to evaluate <__main__.myClass instance at 0x0000000052D64D88> and give me an error. I completely anderstand this error but I would like to know if there is a way to avoid it (with an other function or with an other way to use the function ast.literal_eval)
import ast myText = "{<__main__.myClass instance at 0x0000000052D64D88>: value}" ast.literal_eval(myText) # Error: invalid syntax # Traceback (most recent call last): # File "<maya console>", line 4, in <module> # File "C:\Program Files\Autodesk\Maya2016\bin\python27.zip\ast.py", line 49, in literal_eval # node_or_string = parse(node_or_string, mode='eval') # File "C:\Program Files\Autodesk\Maya2016\bin\python27.zip\ast.py", line 37, in parse # return compile(source, filename, mode, PyCF_ONLY_AST) # File "<unknown>", line 1 # {<__main__.myClass instance at 0x0000000052D64D88>: value} # ^ # SyntaxError: invalid syntax # Thank you in advance for your help !
myTextis going to be fairly regular. 1 Strip the braces. 2. Split on comma. 3. Split each resulting string on the colon, and shove the parts into a dictionary.ast.literal_evaldoes? If your example is verbatim, then neither the key nor the value in your dictionary representation is an actual literal.