3.12. Typing TypeGuard

  • https://github.com/python/typeshed

  • Typeshed contains external type annotations for the Python standard library and Python builtins, as well as third party packages as contributed by people external to those projects.

  • Type Narrowing - the process of refining a type to a more specific type based on certain conditions or checks. This is often used in type checking to ensure that a variable is of a certain type before performing operations on it.

3.12.1. TypeGuard

>>> from typing import TypeGuard
>>>
>>>
>>> def is_list_str(iterable: list[object]) -> TypeGuard[list[str]]:
...     return all(isinstance(x,str) for x in iterable)
>>>
>>>
>>> def run(data: list[object]):
...     if is_list_str(data):
...         print(','.join(data))  # type checker knows that data is narrowed to list[str]
...     else:
...         print('Not a list of strings!')  # type checker thinks that data is still list[object]