4.12. Typing TypeGuard
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.
4.12.1. Problem
str.join()accepts onlylist[str]as a parameter
>>> def is_list_str(iterable: list) -> bool:
... return all(isinstance(x,str) for x in iterable)
>>>
>>>
>>> def run(data: list):
... if is_list_str(data):
... return ','.join(data) # type checker don't know if data is list[str]
... else:
... raise ValueError('Not a list of strings!')
4.12.2. Solution
>>> from typing import TypeGuard
>>>
>>>
>>> def is_list_str(iterable: list) -> TypeGuard[list[str]]:
... return all(isinstance(x,str) for x in iterable)
>>>
>>>
>>> def run(data: list):
... if is_list_str(data):
... return ','.join(data) # type checker knows that data is narrowed to list[str]
... else:
... raise ValueError('Not a list of strings!')