- Daily Dose of Data Science
- Posts
- How To Enforce Type Hints in Python?
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 :)
π 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.
Reply