[docs] [issue31778] ast.literal_eval supports non-literals in Python 3

Nick Coghlan report at bugs.python.org
Sat Oct 14 01:05:42 EDT 2017


Nick Coghlan <ncoghlan at gmail.com> added the comment:

I'm marking this as documentation issue for now, as the operators that literal_eval allows are solely those where constant folding support is needed to correctly handle complex and negative numbers (as noted in the original post):

```
>>> dis.dis("+1")
  1           0 LOAD_CONST               1 (1)
              2 RETURN_VALUE
>>> dis.dis("-1")
  1           0 LOAD_CONST               1 (-1)
              2 RETURN_VALUE
>>> dis.dis("1+1")
  1           0 LOAD_CONST               1 (2)
              2 RETURN_VALUE
>>> dis.dis("1+1j")
  1           0 LOAD_CONST               2 ((1+1j))
              2 RETURN_VALUE
>>> dis.dis("2017-10-10")
  1           0 LOAD_CONST               3 (1997)
              2 RETURN_VALUE
```

So the key promise that literal_eval makes is that it will not permit arbitrary code execution, but the docs should make it clearer that it *does* permit constant folding for addition and subtraction in order to handle the full range of numeric literals.

If folks want to ensure that the input string *doesn't* include a binary operator, then that currently needs to be checked separately with ast.parse:

```
>>> type(ast.parse("2+3").body[0].value) is ast.BinOp
True
>>> type(ast.parse("2017-10-10").body[0].value) is ast.BinOp
True
```

For 3.7+, that check could potentially be encapsulated as an "allow_folding=True" keyword-only parameter (where the default gives the current behaviour, while "allow_folding=False" disables processing of UnaryOp and BinOp), but the docs update is the more immediate need.

----------
assignee:  -> docs at python
components: +Documentation
nosy: +docs at python
versions: +Python 3.6

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue31778>
_______________________________________


More information about the docs mailing list