Proposal: Decimal literals in Python.
Lennart Benschop
lennartb at xs4all.nl
Fri Oct 26 10:54:01 CEST 2007
Python has had the Decimal data type for some time now. The Decimal data
type is ideal for financial calculations. Using this data type would be
more intuitive to computer novices than float as its rounding behaviour
matches more closely what humans expect. More to the point: 0.1 and 0.01
are exact in Decimal and not exact in float.
Unfortunately it is not very easy to access the Decimal data type. To obtain
the decimal number 12.34 one has to do something like this:
import decimal
x=decimal.Decimal("12.34")
Of course we can intruduce a single character function name as an alias for
the Decimal type constructor, but even then we have to use both parentheses
and quotes for each and every decimal constant. We cannot make it shorter
than D("12.34")
With Python 3000 major changes to the language are carried out anyway. My
proposal would require relatively minor changes.
My proposal:
- Any decimal constant suffixed with the letter "D" or "d" will be
interpreted as a literal of the Decimal type. This also goes for
decimal constants with exponential notation.
Examples of decimal literals:
1d
12.34d
1e-3d (equivalent to 0.001d)
1e3d (same value as 1000d, but without trailing zeros).
1.25e5d (same value as 125000d but without trailing zeros).
When we print a decimal number or convert it to a string with str(), a
trailing d should not be added. The repr function does yield strings with a
trailing d.
When decimal numbers are converted from strings, both numbers with and
without a trailing d should be accepted.
If we have decimal literals in the core language, we should probably have a
type constructor in the core namespace, e.g. dec() along with int()
and float(). We then need the decimal module only for the more advanced
stuff like setcontext.
Pros:
- the Decimal data type will be more readily accessible, especially
for novices.
- Traling characters at the end of a literal are already used (the L
for long).
- It does not conflict with the syntax of other numeric constants or
language constructs.
- It does not change the meaning of existing valid literal constants.
Constants that used to be float will continue to do so.
Cons:
- The lexical scanner of the Python interpreter will be slightly more
complex.
- The d suffix for constants with exponential notation is ugly.
- Decimal numbers with exponentail notation like 2e5d could be mistaken
for hex (by humans, not by the parser as hex requires the 0x prefix).
- It requires the decimal module to be part of the core Python
interpreter.
--
Lennart
More information about the Python-list
mailing list