PYTHON: Is there a function similar to ast.literal_eval ()?

I have a problem using ast.literal_eval (). In the example below, I only want to convert the string (myText) to dictionnary. But ast.literal_eval () will try to evaluate <__main__.myClass instance at 0x0000000052D64D88>

and give me an error. I totally agree with this error, but I would like to know if there is a way to avoid this (with a different function or another way of using the ast.literal_eval function)

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!

+3


source to share


1 answer


What you really want to do is flush your data with pickle.dump

and load it with pickle.load

(or an equivalent like json, etc.). Using repr(data)

to reset data will cause such problems.

If you just need to salvage the data you already generated, you might get away with something like the following:

def my_literal_eval(s):
    s = re.sub(r"<__main__.myClass instance at 0x([^>]+)>", r'"<\1>"', s)
    dct = ast.literal_eval(s)
    return {myClass(): v for v in dct.itervalues()}

      

Usage example:



>>> import ast, re
>>> class myClass(object): pass
... 
>>> myText = "{<__main__.myClass instance at 0x0000000052D64D88>: {'name': 'theName'}, <__main__.myClass instance at 0x0000000052D73F48>: {'name': 'theName'}}"
>>> my_literal_eval(myText)
{<__main__.myClass object at 0x7fbdc00a4b90>: {'name': 'theName'}, <__main__.myClass object at 0x7fbdc0035550>: {'name': 'theName'}}

      

This will only work if the instances myClass

do not have any useful information, but are only needed for identification. The idea is to fix the string first, replacing the strings <__main__.myClass instance ...>

with something that can be parsed with ast.literal_eval

, and then replace the ones that have actual instances myClass

if they can be constructed without arguments, which depends on the above assumption.

If this initial assumption is not met, then your data, like Ignacio put it , will be irreversibly damaged, and no smart disassembly will get lost bits.

+3


source







All Articles