[Tutor] Python-list thread: int vs. float

Steven D'Aprano steve at pearwood.info
Sat Feb 11 20:08:15 EST 2017


On Sat, Feb 11, 2017 at 02:28:42PM -0600, boB Stepp wrote:

> Back in the main Python list thread, Marko Rauhamaa suggested
> (https://mail.python.org/pipermail/python-list/2017-February/719322.html):
> 
> "
> ...
> Haven't been following the discussion, but this should be simply:
> 
>    ast.literal_eval("...")
> ...
> "
> 
> This looks like it may do the trick quite concisely:

Nope. Not even close. The problem is that you have to accept ints and 
floats, but reject anything else, and literal_eval does not do that.

py> import ast
py> ast.literal_eval('[1, {}, None, "s", 2.4j, ()]')
[1, {}, None, 's', 2.4j, ()]


literal_eval will parse and evaluate anything that looks like one of:

- int
- float
- string
- bool (True or False)
- None
- complex (e.g. -3.5+4.5j)
- tuple
- list
- dict
- set


so it does *far* more than what the OP requires.

[...]
> That statement about potentially changing with each Python release
> bothers me.  Should I be bothered?

No. In this case, you are parsing a string, and the ast module itself 
parses it to an Abstract Syntax Tree before evaluating literals, so it 
doesn't matter if the AST is different from one version to the next.

You should only care if you generated an AST in (say) Python 3.5, saved 
it in a data file, then read it back in to Python 3.6 and tried to 
evaluate it. That may not succeed.



-- 
Steve


More information about the Tutor mailing list