Skip to content

Commit a30665c

Browse files
committed
move union docs
1 parent a43f1c8 commit a30665c

File tree

1 file changed

+8
-7
lines changed

1 file changed

+8
-7
lines changed

docs/source/cheat_sheet_py3.rst

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -54,10 +54,16 @@ Useful built-in types
5454
# For tuples of variable size, we use one type and ellipsis
5555
x: tuple[int, ...] = (1, 2, 3) # Python 3.9+
5656
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+
5762
from typing import Optional
5863
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
6167
# Mypy understands a value can't be None in an if-statement
6268
if x is not None:
6369
print(x.upper())
@@ -193,11 +199,6 @@ When you're puzzled or when things are complicated
193199
# message with the type; remove it again before running the code.
194200
reveal_type(1) # Revealed type is "builtins.int"
195201
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-
201202
# If you initialize a variable with an empty container or "None"
202203
# you may have to help mypy a bit by providing an explicit type annotation
203204
x: list[str] = []

0 commit comments

Comments
 (0)