Underscores in Python numbers

Bruno Desthuilliers bdesth.quelquechose at free.quelquepart.fr
Sun Nov 20 18:51:09 EST 2005


Raymond Hettinger a écrit :
> Gustav Hållberg wrote:
> 
>>I tried finding a discussion around adding the possibility to have
>>optional underscores inside numbers in Python. This is a popular option
>>available in several "competing" scripting langauges, that I would love
>>to see in Python.
>>
>>Examples:
>>  1_234_567
>>  0xdead_beef
>>  3.141_592
> 
> 
> I suppose it could be done.  OTOH, one could argue that most production
> code has no business hardwiring-in numerical constants greater than 999
> ;-)
> 
That's what I thought at first, but Steven D'Aprano made some good 
points here IMHO, ie :

"""
Not all numeric constants used have simple formulae, or *any* formulae, or
can be calculated on the fly in any reasonable time. Numeric programming
often uses magic constants which truly are "magic" (in the sense that
where they come from requires deep, difficult, and sometimes hidden
knowledge).

Nobody sensible wants to be typing in long strings of digits, but
sometimes it is unavoidable.
"""

and

"""
Another sensible usage case is in the interactive interpreter. If you are
using Python interactively, you may wish to use numeric literals with
large numbers of digits. It is not feasible to read them from a data file,
and using a special converter function is impractical and unnecessary.
"""

So even if it's far from a common use case for *most* Python users, it 
may be a common use case for *some* Python users.

Also, someone mentionned the use of Python as a configuration langage - 
which is probably a much more common use case.


So FWIW, I'd be +1 on adding it *if and only if*:
- it's trivial to implement [1]
- it doesn't break older code

and +1 on the space as group delimiter BTW.


[1]: I never wrote a language by myself, but I've played a bit with 
parsers and lexers, and I _guess_ (which implies I may be wrong !-) it 
wouldn't require much work to add support for a "literal numeric 
grouping" syntax  in Python.



More information about the Python-list mailing list