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:
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.
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.
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.
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:
In modern C++ there is a concept of
ratio
heavily used instd::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.I'm going to add NewType to the article now that I have a reason to :)
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 typelike you can do
ms = NewType('ms', int)
and now if your function requires ams
it won't work with anint
, you need to specifically doms(1000)
. But in python code, it's still just an int. 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 :)
Knowing that it's Python, I'm pretty sure that's easy to patch in on your side as well :)