[Python-ideas] int('0x3241fca1')

Nick Coghlan ncoghlan at gmail.com
Fri Feb 7 10:37:08 CET 2014


On 7 Feb 2014 11:01, "Terry Reedy" <tjreedy at udel.edu> wrote:
>
> On 2/6/2014 5:04 PM, MRAB wrote:
>>
>> On 2014-02-06 21:41, Terry Reedy wrote:
>>>
>>> On 2/6/2014 5:24 AM, Ram Rachum wrote:
>>>>
>>>> What do you think about letting the `int` constructor automatically
>>>> understand the number type without specifying base if given a prefix,
so
>>>> int('0x3414fa') would immediately work without specifying a base of 16?
>>>
>>>
>>> In addition to int(string, 0):
>>>
>>>   >>> number = '0x3414fa'
>>>   >>> eval(number)
>>> 3413242
>>>
>> The disadvantage is that it'll evaluate (run) anything, so it's unsafe
>> in the general case.
>
>
> To evaluate any number expression, but only number expressions, but be
safe against untrusted input, one should use ast.literal_eval, and then
test that the result is a number (either with numbers.Number or adding 0

If you want to support non-integers, yes. But in most cases where prefix
interpretation is of interest, you will specifically want an integer (so
base 0 is the answer), and in other cases, base 10 integer strings are also
valid input for the float or Decimal constructor.

Cheers,
Nick.

>
> import ast
> from numbers import Number
>
> def get_number(prompt = "Input a number: "):
>     s = input(prompt)
>     try:
>         x = ast.literal_eval(s)  # raise ValueError on failure
>         if not isinstance(x, Number):
>             raise ValueError()
>     except ValueError:
>         raise ValueError("'{}' is not a Python number literal".format(s))
from None
>     return x
>
>
> --
> Terry Jan Reedy
>
>
> _______________________________________________
> Python-ideas mailing list
> Python-ideas at python.org
> https://mail.python.org/mailman/listinfo/python-ideas
> Code of Conduct: http://python.org/psf/codeofconduct/
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20140207/5df99f0d/attachment.html>


More information about the Python-ideas mailing list