Discover more from Daily Dose of Data Science
How To Enforce Type Hints in Python?
...and make them more powerful.
When writing Python functions, type hints provide an incredible way to specify explicit information about:
the expected types of function arguments, and
their return type.
Yet, Python NEVER enforces them.
This means that despite having type hints, a function can still accept (or return) a conflicting type.
And Python will not raise any errors/warnings if there is a type mismatch.
To enforce type hints, use Typeguard.
It provides a decorator for type-checking of Python functions.
As a result, in case of conflicting types, an error is raised.
Enforcing type hints can provide an additional layer of type safety. One can catch type violations that could only be detected at run time.
Get started with Typeguard: Docs.
👉 Over to you: Why Python developers didn’t enforce type hints? Let me know your thoughts :)
Thanks for reading Daily Dose of Data Science! Subscribe for free to learn something new and insightful about Python and Data Science every day. Also, get a Free Data Science PDF (350+ pages) with 250+ tips.
👉 Tell the world what makes this newsletter special for you by leaving a review here :)
👉 If you liked this post, don’t forget to leave a like ❤️. It helps more people discover this newsletter on Substack and tells me that you appreciate reading these daily insights. The button is located towards the bottom of this email.
👉 If you love reading this newsletter, feel free to share it with friends!
👉 Sponsor the Daily Dose of Data Science Newsletter. More info here: Sponsorship details.
Find the code for my tips here: GitHub.