Built-in types
- from typing import List, Set, Dict, Tuple, Text, Optional
-
- # For simple built-in types, just use the name of the type
- x = 1 # type: int
- x = 1.0 # type: float
- x = True # type: bool
- x = "test" # type: str
- x = u"test" # type: unicode
-
- # For collections, the name of the type is capitalized, and the
- # name of the type inside the collection is in brackets
- x = [1] # type: List[int]
- x = {6, 7} # type: Set[int]
-
- # For mappings, we need the types of both keys and values
- x = {'field': 2.0} # type: Dict[str, float]
-
- # For tuples, we specify the types of all the elements
- x = (3, "yes", 7.5) # type: Tuple[int, str, float]
-
- # For textual data, use Text
- # ("Text" means "unicode" in Python 2 and "str" in Python 3)
- x = [u"one", u"two"] # type: List[Text]
-
- # Use Optional[] for values that could be None
- x = some_function() # type: Optional[str]
- # Mypy understands a value can't be None in an if-statement
- if x is not None:
- print x.upper()
- # If a value can never be None due to some invariants, use an assert
- assert x is not None
- print x.upper()