Python Type Hints - What’s the point of NoReturn?2021-05-20
Sometimes functions never return, for example by always raising an exception.
For such functions’ return types, we can “get away” with using
None, but it’s best to use the special
This allows Mypy to better find unreachable code (as covered previously).
It also shows future readers that the lack of return is intentional.
For example, take this code:
always_raise() means that we’ll have a
print("Ok!") cannot be reached.
But if we check with Mypy, it cannot detect this:
Let’s update the code to instead use
Now Mypy tells us the
print() will never run:
It’s best to use
NoReturn for any function that never returns.
These includes functions with infinite loops or use of OS API’s that end the process:
We are now past the point of
Want better tests? Check out my book Speed Up Your Django Tests which teaches you to write faster, more accurate tests.
One summary email a week, no spam, I pinky promise.
- Python Type Hints - Use object instead of Any
- Python Type Hints - How to use Mypy’s unreachable code detection
Tags: mypy, python
© 2021 All rights reserved.