Introduction To Python Type Annotations

The syntax is similar with one difference: the type of each element of the tuple is indicated in square brackets separately.If you plan to use a tuple similar to the list: store an unknown number of similar elements, you can use the ellipsis (…).Tuple annotation without specifying element types works like Tuple [Any, …]price_container: Tuple[int] = (1,)price_container = ("hello") # Incompatible types in assignment (expression has type "str", variable has type "Tuple[int]")price_container = (1, 2) # Incompatible types in assignment (expression has type "Tuple[int, int]", variable has type "Tuple[int]")price_with_title: Tuple[int, str] = (1, "hello")prices: Tuple[int, …] = (1, 2)prices = (1, )prices = (1, "str") # Incompatible types in assignment (expression has type "Tuple[int, str]", variable has type "Tuple[int, …]")something: Tuple = (1, 2, "hello")DictionariesDictionaries use typing.Dict..The key type and value type are annotated separately:book_authors: Dict[str, str] = {"Fahrenheit 451": "Bradbury"}book_authors["1984"] = 0 # Incompatible types in assignment (expression has type "int", target has type "str")book_authors[1984] = "Orwell" # Invalid index type "int" for "Dict[str, str]"; expected type "str"Similarly, typing.DefaultDict and typing.OrderedDict are used.The result of the functionTo specify the type of the result of the function, you can use any annotation..But there are some special cases.If the function returns nothing (for example, like print), its result is always None..For annotations we also use None.Valid options for completing such a function are: explicitly returning None, returning without specifying a value, and ending without calling return.def nothing(a: int) -> None: if a == 1: return elif a == 2: return None elif a == 3: return "" # No return value expected else: passIf the function never returns control (for example, as sys.exit), you should use the NoReturn annotation:def forever() -> NoReturn: while True: passIf this is a generator function, that is, its body contains a yield operator, you can use the Iterable[T] or Generator [YT, ST, RT] annotation for the return value:def generate_two() -> Iterable[int]: yield 1 yield "2" # Incompatible types in "yield" (actual type "str", expected type "int")ConclusionsFor many situations in the typing module there are suitable types, however, I will not consider everything since the behavior is similar to the one considered.For example, there is an Iterator as a generic version for collections.abc.Iterator, typing.SupportsInt to indicate that an object supports the __int__ method, or Callable for functions and objects that support the __call__ methodThe standard also defines the format of annotations in the form of comments and stub files that contain information only for static analyzers.. More details

Leave a Reply