The handful of times I’ve reached for typing.TypeGuard in Python, I’ve always been confused by its behavior and ended up ditching it with

TypeIs does what I thought TypeGuard would do in Python

submited by
Style Pass
2024-04-28 07:00:04

The handful of times I’ve reached for typing.TypeGuard in Python, I’ve always been confused by its behavior and ended up ditching it with a # type: ignore comment.

For the uninitiated, TypeGuard allows you to apply custom type narrowing1. For example, let’s say you have a function named pretty_print that accepts a few different types and prints them differently onto the console:

If you run it through mypy, in each branch, the type checker automatically narrows the type and knows exactly what the type of val is. You can test the narrowed type in each branch with the typing.assert_type function.

This works well for 99% of cases, but occasionally, you need to check an incoming value more thoroughly to determine its type and want to take action based on the narrowed type. In those cases, just using isinstance may not be sufficient. So, you need to factor out the complex type checking logic into a separate function and return a boolean depending on whether the inbound value satisfies all the criteria to be of the expected type. For example:

Here, is_person first checks that the inbound dictionary conforms to the structure of the Person typeddict and then verifies that name is at least 1 character long and age is between 0 and 150.

Leave a Comment