Read the original on my personal blog
Mypy is a static type checker for Python. It acts as a linter, that allows you to write statical...
For further actions, you may consider blocking this person and/or reporting abuse
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.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 :)
I'm going to add NewType to the article now that I have a reason to :)
Thanks for this very interesting article. Same as Artalus below, I use types a lot in all my recent Py modules, but I learned a lot of new tricks by reading this.
Superb!
I am using
pyproject.toml
as a configuration file andstubs
folder for my custom-types for third party packages.Running from CLI,
mypy .
runs successfully. but when it runs at pre-commit, it fails (probably assuming stubs not present and thus return type isAny
)Great post! I use type hinting all the time in python, it helps readability in larger projects.
In JavaScript ecosystem, some third-party libraries have no Typescript support at all or sometimes have incorrect types which can be a major hassle during development. How's the status of mypy in Python ecosystem?
Mypy is still fairly new, it was essentially unknown as early as 4 years ago. But the good thing about both of them is that you can add types to projects even if the original authors don't, using type stub files, and most common libraries have either type support or stubs available :)
Not much different than TypeScript honestly.
What a great post! This is the most comprehensive article about mypy I have ever found, really good. Congratulations!
Thanks a lot, that's what I aimed it to be :D
Used mypy for the first time today and sometimes quite obscur. Many, many thanks for your GREAT article !