Usage of ast.

Jussi Piitulainen jussi.piitulainen at helsinki.fi
Mon Feb 27 08:19:49 EST 2017


Vincent Vande Vyvre writes:

> I've this strange error:
>
> Python 3.4.3 (default, Nov 17 2016, 01:08:31)
> [GCC 4.8.4] on linux
> Type "help", "copyright", "credits" or "license" for more information.
>>>> import ast
>>>> l = "print('hello world')"
>>>> ast.literal_eval(l)
> Traceback (most recent call last):
>   File "<stdin>", line 1, in <module>
>   File "/usr/lib/python3.4/ast.py", line 84, in literal_eval
>     return _convert(node_or_string)
>   File "/usr/lib/python3.4/ast.py", line 83, in _convert
>     raise ValueError('malformed node or string: ' + repr(node))
> ValueError: malformed node or string: <_ast.Call object at 0x7fcf955871d0>
>
>
> Is it an import question ?

print('hello world') is not a literal.

Literals are expressions that somehow stand for themselves. Try
help(ast.literal_eval) for a more detailed definition.

literal_eval('x') # not ok: x is not a literal
literal_eval('"x"') # ok: "x" is a literal



More information about the Python-list mailing list