[Python-ideas] SI scale factors in Python

Nick Coghlan ncoghlan at gmail.com
Fri Aug 26 04:31:30 EDT 2016


On 26 August 2016 at 16:54, Steven D'Aprano <steve at pearwood.info> wrote:
> At best, we can choose descriptive variable names that hint what the
> correct dimensions should be:
>
>     weight_of_contents + weight_of_container
>
>
> The argument that units would make it easier for the programmer to spot
> errors is, I think, invalid, because the programmer will hardly ever get
> to see the units.

This is based on a narrowly construed definition of "programming"
though. It makes more sense in the context of interactive data
analysis and similar activities, where Python is being used as a
scripting language, rather than as a full-fledged applications
programming language.

So let's consider the following hypothetical:

1. We add SI multiplier support to the numeric literal syntax, with
"E" unilaterally replaced with "X" (for both input and output) to
avoid the ambiguity with exponential notation
2. One or more domain specific libraries adopt Ivan Levkivskyi's
suggestion of using PEP 526 to declare units

Then Ken's example becomes:

    from circuit_units import A, V, Ohm, seconds

    delta: A
    for delta in [-500n, 0, 500n]:
        input: A = 2.75u + delta
        wait(seconds(1u))
        expected: V = Ohm(100k)*input
        tolerance: V = 2.2m
        fails = check_output(expected, tolerance)
        print('%s: I(in)=%rA, measured V(out)=%rV, expected
V(out)=%rV, diff=%rV.' % (
            'FAIL' if fails else 'pass',
            input, get_output(), expected, get_output() - expected
        ))

The only new pieces there beyond PEP 526 itself are the SI unit
multiplier on literals, and the type annotations declared in the
circuit_units module. To actually get a typechecker to be happy with
the code, Ohm.__mul__ would need to be overloaded as returning a V
result when the RHS is categorised as A.

An environment focused on circuit simulation could pre-import some of
those symbols so users didn't need to do it explicitly.

Cheers,
Nick.

-- 
Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia


More information about the Python-ideas mailing list