Built-in types

  1. from typing import List, Set, Dict, Tuple, Text, Optional
  2.  
  3. # For simple built-in types, just use the name of the type
  4. x = 1 # type: int
  5. x = 1.0 # type: float
  6. x = True # type: bool
  7. x = "test" # type: str
  8. x = u"test" # type: unicode
  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 = [1] # type: List[int]
  13. x = {6, 7} # type: Set[int]
  14.  
  15. # For mappings, we need the types of both keys and values
  16. x = {'field': 2.0} # type: Dict[str, float]
  17.  
  18. # For tuples, we specify the types of all the elements
  19. x = (3, "yes", 7.5) # type: Tuple[int, str, float]
  20.  
  21. # For textual data, use Text
  22. # ("Text" means "unicode" in Python 2 and "str" in Python 3)
  23. x = [u"one", u"two"] # type: List[Text]
  24.  
  25. # Use Optional[] for values that could be None
  26. x = some_function() # type: Optional[str]
  27. # Mypy understands a value can't be None in an if-statement
  28. if x is not None:
  29. print x.upper()
  30. # If a value can never be None due to some invariants, use an assert
  31. assert x is not None
  32. print x.upper()