I'm trying to achieve the same behavior with ast.literal_eval as with eval, is it possible somehow?
import ast
class MyClass():
...
class_string = "MyClass"
eval_clas = eval(class_string)
print(eval_clas)
ast_class = ast.literal_eval(class_string)
print(ast_class)
the output of eval_class:
<class '__main__.MyClass'>
When I try to do the same thing with literal_eval I'm getting
ValueError: malformed node or string: <_ast.Name object at 0x7f1670b9a520>
CodePudding user response:
ast.literal_eval
docs claims that
Safely evaluate an expression node or a string containing a Python literal or container display. The string or node provided may only consist of the following Python literal structures: strings, bytes, numbers, tuples, lists, dicts, sets, booleans,
None
andEllipsis
.
custom classes are not supported by that function, as they are not enumerated