[Python-ideas] eval_literal

Chris Angelico rosuav at gmail.com
Mon Jun 13 18:17:54 EDT 2016


On Tue, Jun 14, 2016 at 8:13 AM,  <jab at math.brown.edu> wrote:
> (Riffing off some discussion in another thread, I had another idea I
> wanted to throw out there.)
>
> Given that Eval Really Is Dangerous[1], has something like this ever
> been considered?:
>
>>>> int(str(42))
> 42
>>>> float(str(42.0))
> 42.0
>>>> bool(str(False))  # :(
> True
>>>> eval_literal('42')
> 42
>>>> eval_literal('42.0')
> 42.0
>>>> eval_literal('False')  # :)
> False
>>>> eval_literal('', default=False)  # shout out to PEP 463 / Michael Selik
> False
>
> i.e. An extremely limited version of eval, possibly just for literals
> or even literal atoms, that would make it safe?
>

Check out ast.literal_eval:

https://docs.python.org/3/library/ast.html#ast.literal_eval

It's capable of evaluating all forms of literal, plus a variety of
things that people kinda expect to be literals but aren't, plus some
larger constructs that definitely aren't literals but are still very
useful and safe (eg list display).

ChrisA


More information about the Python-ideas mailing list