[Python-ideas] Units in type hints
Steven D'Aprano
steve at pearwood.info
Thu May 14 13:59:58 CEST 2015
On Thu, May 14, 2015 at 02:03:39PM +0300, Koos Zevenhoven wrote:
> Hi all,
>
> How about extending the type annotations for int, float and complex to
> optionally include also a unit?
I really, really like the idea of having unit-aware calculations.
But this is not the way to do it. See below:
> For instance,
>
> def sleep(duration : Float['s']):
> ...
>
> Now the type checker could catch the error of trying to pass the sleep
> duration in milliseconds, Float['ms'].
But that's not an error. Calling sleep(weight_in_kilograms) is an error.
But calling sleep(milliseconds(1000)) should be the same as calling
sleep(seconds(1)). If the user has to do the conversion themselves,
that's a source of error:
sleep(time_in_milliseconds / 1000) # convert to seconds
If you think that's too obvious an error for anyone to make, (1) you're
wrong, I've made that error, yes even that simple, and (2) you should
try it with more complex sets of units. How many pound-foot per minute
squared in a newton?
Having the language support unit calculations is not just to catch the
wrong dimensions (passing a weight where a time is needed), but to
manage unit conversions automatically without the user being responsible
for getting the conversion right. A type checker is the wrong tool for
the job.
If you want to see what a good unit-aware language should be capable of,
check out:
- Frink: https://futureboy.us/frinkdocs/
- the HP-28 and HP-48 series of calculators;
- the Unix/Linux "units" utility.
There are also some existing Python libraries which do unit
calculations. You should look into them.
--
Steve
More information about the Python-ideas
mailing list