[Python-ideas] Units in type hints
Koos Zevenhoven
koos.zevenhoven at aalto.fi
Thu May 14 13:03:39 CEST 2015
Hi all,
How about extending the type annotations for int, float and complex to
optionally include also a unit?
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']. This would also be useful for
documentation, avoiding the 'need' for having names like duration_s. At
least the notation with square brackets would resemble the way units are
often written in science.
Another example:
def calculate_travel_time(distance: Float['km']) -> Float['h']:
speed = get_current_speed() # type: Float['km/h']
return distance / speed
Now, if you try to pass the distance in miles, or Float['mi'], the type
checker would catch the error. Note that the type checker would also
understand that 'km' divided by 'km/h' becomes 'h'. Or should these be
something like units.km / units.h?
But if you do have your distance in miles, you do
calculate_travel_time(units.convert(distance_mi, 'mi', 'km'))
and the type checker and programmer get what they want.
Anyone interested?
-- Koos
More information about the Python-ideas
mailing list