[Python-ideas] SI scale factors in Python

Chris Angelico rosuav at gmail.com
Thu Aug 25 00:47:42 EDT 2016


On Thu, Aug 25, 2016 at 2:28 PM, Ken Kundert
<python-ideas at shalmirane.com> wrote:
>     I propose that support for SI scale factors be added to Python. This would
> be very helpful for any program that heavily uses real numbers, such as those
> involved with scientific and engineering computation. There would be two primary
> changes.  First, the lexer would be enhanced to take real literals with the
> following forms:
>
>     c1 = 1nF          (same as: c1 = 1e-9        # F )
>     c = 299.79M       (same as: c = 299.79e6         )
>     f_hy = 1.4204GHz  (same as: f_hy = 1.4204e9  # Hz)
>
> Basically a scale factor and units may follow a number, both of which are
> optional, but if the units are given the scale factor must also be given. Any
> units given could be kept with the number and would be accessible through an
> attribute or method call, or if it is felt that the cost of storing the units
> are too high, it may simply be discarded, in which case it is simply serving as
> documentation.

If units are retained, what you have is no longer a simple number, but
a value with a unit, and is a quite different beast. (For instance,
addition would have to cope with unit mismatches (probably by throwing
an error), and multiplication would have to combine the units (length
* length = area).) That would be a huge new feature. I'd be inclined
to require, for simplicity, that the scale factor and the unit be
separated with a hash:

c1 = 1n#F
c = 299.79M
f_hy = 1.4204G#Hz

It reads almost as well as "GHz" does, but is clearly non-semantic.
The resulting values would simply be floats, and the actual tag would
be discarded - there'd be no difference between 1.4204G and 1420.4M,
and the %q formatting code would render them the same way.

Question, though: What happens with exa-? Currently, if the parser
sees "1E", it'll expect to see another number, eg 1E+1 == 10.0. Will
this double meaning cause confusion?

ChrisA


More information about the Python-ideas mailing list