@@ -34,36 +34,27 @@ Useful built-in types
34
34
35
35
.. code-block :: python
36
36
37
- from typing import List, Set, Dict, Tuple, Optional
38
-
39
37
# For most types, just use the name of the type
40
38
x: int = 1
41
39
x: float = 1.0
42
40
x: bool = True
43
41
x: str = " test"
44
42
x: bytes = b " test"
45
43
46
- # For collections, the type of the collection item is in brackets
47
- # (Python 3.9+)
44
+ # For collections on Python 3.9+, the type of the collection item is in brackets
48
45
x: list[int ] = [1 ]
49
46
x: set[int ] = {6 , 7 }
50
47
51
- # In Python 3.8 and earlier, the name of the collection type is
52
- # capitalized, and the type is imported from the 'typing' module
53
- x: List[int ] = [1 ]
54
- x: Set[int ] = {6 , 7 }
55
-
56
48
# For mappings, we need the types of both keys and values
57
49
x: dict[str , float ] = {" field" : 2.0 } # Python 3.9+
58
- x: Dict[str , float ] = {" field" : 2.0 }
59
50
60
51
# For tuples of fixed size, we specify the types of all the elements
61
52
x: tuple[int , str , float ] = (3 , " yes" , 7.5 ) # Python 3.9+
62
- x: Tuple[int , str , float ] = (3 , " yes" , 7.5 )
63
53
64
54
# For tuples of variable size, we use one type and ellipsis
65
55
x: tuple[int , ... ] = (1 , 2 , 3 ) # Python 3.9+
66
- x: Tuple[int , ... ] = (1 , 2 , 3 )
56
+
57
+ from typing import Optional
67
58
68
59
# Use Optional[] for values that could be None
69
60
x: Optional[str ] = some_function()
@@ -74,6 +65,16 @@ Useful built-in types
74
65
assert x is not None
75
66
print (x.upper())
76
67
68
+ from typing import List, Set, Dict, Tuple
69
+
70
+ # In Python 3.8 and earlier, the name of the collection type is
71
+ # capitalized, and the type is imported from the 'typing' module
72
+ x: List[int ] = [1 ]
73
+ x: Set[int ] = {6 , 7 }
74
+ x: Dict[str , float ] = {" field" : 2.0 }
75
+ x: Tuple[int , str , float ] = (3 , " yes" , 7.5 )
76
+ x: Tuple[int , ... ] = (1 , 2 , 3 )
77
+
77
78
Functions
78
79
*********
79
80
@@ -143,7 +144,9 @@ When you're puzzled or when things are complicated
143
144
# message with the type; remove it again before running the code.
144
145
reveal_type(1 ) # Revealed type is "builtins.int"
145
146
146
- # Use Union when something could be one of a few types
147
+ # On Python 3.10, use the | operator when something could be one of a few types
148
+ x: list[int | str ] = [3 , 5 , " test" , " fun" ]
149
+ # On earlier versions, use Union
147
150
x: list[Union[int , str ]] = [3 , 5 , " test" , " fun" ]
148
151
149
152
# If you initialize a variable with an empty container or "None"
0 commit comments