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

boB Stepp robertvstepp at gmail.com
Sat Feb 11 23:08:37 EST 2017


On Sat, Feb 11, 2017 at 7:08 PM, Steven D'Aprano <steve at pearwood.info> wrote:
> 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, ()]

My intent was to follow up with
type(ast.literal_eval(string_input_from_user)) and if that does not
come out 'int' or 'float', then it can be rejected as invalid input
from the user.  In your example type() would return a list, which
would be invalid input for the OP's case.  Of course this seems like
swatting a gnat with a sledge hammer, but it still seems that the
combination of checking the return of
type(ast.literal_eval(user_input)) does the job since everything that
is not float or int can be rejected as invalid input, and the float
case can get its special error message.

Or am I missing something?

boB


More information about the Tutor mailing list