DEV Community

Discussion on: The Comprehensive Guide to mypy

Collapse
 
artalus profile image
Artalus

I thought I use typehints a lot, but I have not yet encountered half of the things described here! Thank you for such an awesome and thorough article :3

Question. What do you think would be best approach on separating types for several concepts that share the same builtin type underneath? To avoid something like:

time_seconds: int = 1
time_ms: int = 1000
weight_kg = 61
def foo(start_ms: int, end_ms: int): ...
foo(time_seconds, weight_kg)
Enter fullscreen mode Exit fullscreen mode

In modern C++ there is a concept of ratio heavily used in std::chrono to convert seconds in milliseconds and vice versa, and there are strict-typing libraries for various SI units. Would be nice to have some alternative for that in python.

Collapse
 
tusharsadhwani profile image
Tushar Sadhwani

I'm going to add NewType to the article now that I have a reason to :)

Collapse
 
tusharsadhwani profile image
Tushar Sadhwani • Edited

oh yea, that's the one thing that I omitted from the article because I couldn't think up a reason to use it. mypy has NewType which less you subtype any other type

like you can do ms = NewType('ms', int) and now if your function requires a ms it won't work with an int, you need to specifically do ms(1000). But in python code, it's still just an int. I think that's exactly what you need.

Collapse
 
artalus profile image
Artalus

I think that's exactly what you need.

Totally! The ultimate syntactic sugar now would be an option to provide automatic "conversion constructors" for those custom types, like def __ms__(seconds: s): return ms(s*1000) - but that's not a big deal compared to ability to differentiate integral types semantically.

Thank you :)

Thread Thread
 
tusharsadhwani profile image
Tushar Sadhwani

Knowing that it's Python, I'm pretty sure that's easy to patch in on your side as well :)