Usage of ast.

Chris Angelico rosuav at gmail.com
Mon Feb 27 08:09:54 EST 2017


On Mon, Feb 27, 2017 at 11:57 PM, Vincent Vande Vyvre
<vincent.vande.vyvre at telenet.be> wrote:
> 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 ?

The message is a little confusing, but the error comes from the fact
that literal_eval permits a very few legal operations, and calling a
function isn't one of them. So when you try to evaluate the "literal"
that you've given it, you get back an error saying that a Call is
'malformed'. More accurate would be to say that it's not permitted.

ChrisA



More information about the Python-list mailing list