Python type hints: modernized error messages in Mypy 1.4.0
Mypy 1.4.0 was released last week (2023-06-20). I’m happy to see it includes three improvements that modernize error messages with newer type hint syntax:
- Use lower-case built-in collection types such as
list[…]
instead ofList[…]
in errors when targeting Python 3.9+ (Max Murin, PR 15070) - Use
X | Y
union syntax in error messages when targeting Python 3.10+ (Omar Silva, PR 15102) - Use
type
instead ofType
in errors when targeting Python 3.9+ (Rohit Sanjay, PR 15139)
I summarized these syntax changes in a post last year.
Here’s a quick example which triggers affected error messages:
listicle: list[int] = (1,)
numericle: int | str = 1.0
typicle: type[str] = bytes
Mypy 1.3.0 reports with old syntax:
$ mypy example.py
example.py:1: error: Incompatible types in assignment (expression has type "Tuple[int]", variable has type "List[int]") [assignment]
example.py:3: error: Incompatible types in assignment (expression has type "float", variable has type "Union[int, str]") [assignment]
example.py:5: error: Incompatible types in assignment (expression has type "Type[bytes]", variable has type "Type[str]") [assignment]
Found 3 errors in 1 file (checked 1 source file)
…whilst 1.4.1 is nice and modern:
$ mypy example.py
example.py:1: error: Incompatible types in assignment (expression has type "tuple[int]", variable has type "list[int]") [assignment]
example.py:3: error: Incompatible types in assignment (expression has type "float", variable has type "int | str") [assignment]
example.py:5: error: Incompatible types in assignment (expression has type "type[bytes]", variable has type "type[str]") [assignment]
Found 3 errors in 1 file (checked 1 source file)
Brilliant! Some welcome incremental improvements to our Python typing infrastructure.
To modernize the typing syntax in your codebase, check out the pyupgrade tool. Check out my previous post for a small guide on using it.
Fin
Thanks to Max Murin, Omar Silva, and Rohit Sanjay for authoring these PR’s, and Jukka Lehtosalo and Shantanu for reviewing them.
May you continue to enjoy new typing features,
—Adam
Read my book Boost Your Git DX to Git better.
One summary email a week, no spam, I pinky promise.
Related posts: