Usage of ast.

Chris Angelico rosuav at gmail.com
Mon Feb 27 09:37:22 EST 2017


On Tue, Feb 28, 2017 at 1:18 AM, Jon Ribbens <jon+usenet at unequivocal.eu> wrote:
> On 2017-02-27, Vincent Vande Vyvre <vincent.vande.vyvre at telenet.be> wrote:
>> Le 27/02/17 à 14:09, Chris Angelico a écrit :
>>> 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.
>>
>> OK, it's coherent with the secure execution.
>
> "execution" isn't really the right way to describe literal_eval().
> It isn't an code executor or even an expression evaluator, all it
> does is turns a Python literal in source form into the value that
> source represents. You can't do literal_eval("2*3") for example,
> because that's an expression not a literal.
>
> The only reason you can do literal_eval("2+3") (in Python>=3.2)
> is because of a side effect of the fact that complex number literals
> are, well, complex ("2+3j"), and the support for +/- wasn't restricted
> to complex literals only.

Actually it does execute, as you can see from the source code. The
name "literal" is slightly incorrect technically, as it will run some
code that isn't actually a literal (nor even covered by constant
folding, which "2+3j" is - it's two literals and a binary operator,
but constant folded at compile time).

>>> ast.literal_eval("[1,2,3]")
[1, 2, 3]

This isn't a literal, and it's evaluated by literal_eval. It's
basically a "safe eval of simple expressions".

ChrisA



More information about the Python-list mailing list