@@ -54,10 +54,16 @@ Useful built-in types
54
54
# For tuples of variable size, we use one type and ellipsis
55
55
x: tuple[int , ... ] = (1 , 2 , 3 ) # Python 3.9+
56
56
57
+ # On Python 3.10+, use the | operator when something could be one of a few types
58
+ x: list[int | str ] = [3 , 5 , " test" , " fun" ]
59
+ # On earlier versions, use Union
60
+ x: list[Union[int , str ]] = [3 , 5 , " test" , " fun" ]
61
+
57
62
from typing import Optional
58
63
59
- # Use Optional[] for values that could be None
60
- x: Optional[str ] = some_function()
64
+ # Use Optional[X] for a value that could be None
65
+ # (Optional[X] is the same as X | None or Union[X, None])
66
+ x: Optional[str ] = " something" if some_condition() else None
61
67
# Mypy understands a value can't be None in an if-statement
62
68
if x is not None :
63
69
print (x.upper())
@@ -193,11 +199,6 @@ When you're puzzled or when things are complicated
193
199
# message with the type; remove it again before running the code.
194
200
reveal_type(1 ) # Revealed type is "builtins.int"
195
201
196
- # On Python 3.10, use the | operator when something could be one of a few types
197
- x: list[int | str ] = [3 , 5 , " test" , " fun" ]
198
- # On earlier versions, use Union
199
- x: list[Union[int , str ]] = [3 , 5 , " test" , " fun" ]
200
-
201
202
# If you initialize a variable with an empty container or "None"
202
203
# you may have to help mypy a bit by providing an explicit type annotation
203
204
x: list[str ] = []
0 commit comments