Built-in types

  1. from typing import List, Set, Dict, Tuple, Optional
  2.  
  3. # For simple built-in types, just use the name of the type
  4. x: int = 1
  5. x: float = 1.0
  6. x: bool = True
  7. x: str = "test"
  8. x: bytes = b"test"
  9.  
  10. # For collections, the name of the type is capitalized, and the
  11. # name of the type inside the collection is in brackets
  12. x: List[int] = [1]
  13. x: Set[int] = {6, 7}
  14.  
  15. # Same as above, but with type comment syntax
  16. x = [1] # type: List[int]
  17.  
  18. # For mappings, we need the types of both keys and values
  19. x: Dict[str, float] = {'field': 2.0}
  20.  
  21. # For tuples of fixed size, we specify the types of all the elements
  22. x: Tuple[int, str, float] = (3, "yes", 7.5)
  23.  
  24. # For tuples of variable size, we use one type and ellipsis
  25. x: Tuple[int, ...] = (1, 2, 3)
  26.  
  27. # Use Optional[] for values that could be None
  28. x: Optional[str] = some_function()
  29. # Mypy understands a value can't be None in an if-statement
  30. if x is not None:
  31. print(x.upper())
  32. # If a value can never be None due to some invariants, use an assert
  33. assert x is not None
  34. print(x.upper())