Python type hints: modernized error messages in Mypy 1.4.0

Three upward slopes for three improvements.

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:

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.


Subscribe via RSS, Twitter, Mastodon, or email:

One summary email a week, no spam, I pinky promise.

Related posts:

Tags: ,