Skip to content

Commit d0c380d

Browse files
committed
Improve cheat sheet
- Mention PEP 604 unions - Separate out the 3.8 stuff to keep things readable Linking python#13681
1 parent dbe9a88 commit d0c380d

File tree

1 file changed

+16
-13
lines changed

1 file changed

+16
-13
lines changed

docs/source/cheat_sheet_py3.rst

Lines changed: 16 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -34,36 +34,27 @@ Useful built-in types
3434

3535
.. code-block:: python
3636
37-
from typing import List, Set, Dict, Tuple, Optional
38-
3937
# For most types, just use the name of the type
4038
x: int = 1
4139
x: float = 1.0
4240
x: bool = True
4341
x: str = "test"
4442
x: bytes = b"test"
4543
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
4845
x: list[int] = [1]
4946
x: set[int] = {6, 7}
5047
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-
5648
# For mappings, we need the types of both keys and values
5749
x: dict[str, float] = {"field": 2.0} # Python 3.9+
58-
x: Dict[str, float] = {"field": 2.0}
5950
6051
# For tuples of fixed size, we specify the types of all the elements
6152
x: tuple[int, str, float] = (3, "yes", 7.5) # Python 3.9+
62-
x: Tuple[int, str, float] = (3, "yes", 7.5)
6353
6454
# For tuples of variable size, we use one type and ellipsis
6555
x: tuple[int, ...] = (1, 2, 3) # Python 3.9+
66-
x: Tuple[int, ...] = (1, 2, 3)
56+
57+
from typing import Optional
6758
6859
# Use Optional[] for values that could be None
6960
x: Optional[str] = some_function()
@@ -74,6 +65,16 @@ Useful built-in types
7465
assert x is not None
7566
print(x.upper())
7667
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+
7778
Functions
7879
*********
7980

@@ -143,7 +144,9 @@ When you're puzzled or when things are complicated
143144
# message with the type; remove it again before running the code.
144145
reveal_type(1) # Revealed type is "builtins.int"
145146
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
147150
x: list[Union[int, str]] = [3, 5, "test", "fun"]
148151
149152
# If you initialize a variable with an empty container or "None"

0 commit comments

Comments
 (0)