Skip to content

Commit c8b3916

Browse files
gnpricegvanrossum
authored andcommitted
More improvements to cheat sheet (#1659)
* More improvements to cheat sheet I made a revision pass through the whole document, and made several kinds of changes: * Organize it all in hopes of making things easier to find with thematic groupings, headers, spacing, and putting the key words at the start of each description. * Give the descriptions more of a common style. * Explain a few things like `reveal_type` and `Sequence` a little more fully. * Cut the redundant `Tuple` example. * Add descriptions for the class-definition example. * Add a description for the generator-function example, and change its return-type annotation from `Iterator` to `Iterable`. That gets us out of trying to explain the difference between those, as `Iterable` is the one we mention elsewhere for function parameters. And as far as I can see, there isn't a reason we need to recommend `Iterator` instead here. I'd have liked also to switch from recommending `six.text_type` to `typing.Text`, but that should wait until 3.5.2, with `Text`, is out.
1 parent 939ef02 commit c8b3916

File tree

1 file changed

+123
-69
lines changed

1 file changed

+123
-69
lines changed

docs/source/cheat_sheet.rst

Lines changed: 123 additions & 69 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
Mypy syntax cheat sheet (Python 2)
22
==================================
33

4-
This document is a quick cheat sheet showing how the PEP-484 type
4+
This document is a quick cheat sheet showing how the PEP 484 type
55
language represents various common types in Python 2.
66

77
.. note::
@@ -11,121 +11,175 @@ language represents various common types in Python 2.
1111
many of the examples have a dual purpose: show how to write the
1212
annotation, and show the inferred types.
1313

14+
15+
Built-in types
16+
**************
17+
1418
.. code-block:: python
1519
16-
from typing import List, Dict, Set, Tuple, Union, Optional, Callable, Match
17-
from six import text_type
20+
from typing import List, Set, Dict, Tuple, Optional
21+
import six
1822
19-
# For builtin types, just use the name of the type
23+
# For simple built-in types, just use the name of the type.
2024
x = 1 # type: int
2125
x = 1.0 # type: float
2226
x = "test" # type: str
2327
x = u"test" # type: unicode
2428
25-
# Print an error message giving the type of x (it's also a runtime
26-
# error, so don't leave it in)
27-
reveal_type(x)
28-
2929
# For collections, the name of the type is capitalized, and the
30-
# name of the type in the collection is in brackets.
30+
# name of the type inside the collection is in brackets.
3131
x = [1] # type: List[int]
3232
x = set([6, 7]) # type: Set[int]
33-
# For mappings, we need the types of both keys and values
33+
34+
# For mappings, we need the types of both keys and values.
3435
x = dict(field=2.0) # type: Dict[str, float]
35-
# For tuples, we specify the types of all the elements
36+
37+
# For tuples, we specify the types of all the elements.
3638
x = (3, "yes", 7.5) # type: Tuple[int, str, float]
3739
38-
# six.text_type is str/unicode in Python 2 and string but not bytes in Python 3
39-
x = ["string", u"unicode"] # type: List[text_type]
40-
# If something could be one of a few types, use Union
41-
x = [3, 5, "test", "fun"] # type: List[Union[int, str]]
42-
x = re.match(r'[0-9]+', "15") # type: Match[str]
40+
# For textual data, we generally use six.text_type.
41+
# This is `unicode` in Python 2 and `str` in Python 3.
42+
x = ["string", u"unicode"] # type: List[six.text_type]
43+
44+
# Use Optional for values that could be None.
45+
input_str = f() # type: Optional[str]
46+
if input_str is not None:
47+
print input_str
4348
44-
# If you don't know the type of something, you can use Any
45-
x = mystery_function() # type: Any
46-
# And if you want to have something not be type-checked, you can
47-
# use ignore to suppress mypy warnings for a given line
48-
# Ideally, one would never use this
49-
x = confusing_function() # type: ignore
5049
51-
# This is how you annotate a function definition
50+
Functions
51+
*********
52+
53+
.. code-block:: python
54+
55+
from typing import Callable, Iterable
56+
57+
# This is how you annotate a function definition.
5258
def stringify(num):
5359
# type: (int) -> str
5460
"""Your function docstring goes here after the type definition."""
5561
return str(num)
5662
57-
# And here's how you specify multiple arguments
63+
# And here's how you specify multiple arguments.
5864
def plus(num1, num2):
5965
# type: (int, int) -> int
6066
return num1 + num2
6167
62-
# Add type annotations for kwargs as though they were positional args
68+
# Add type annotations for kwargs as though they were positional args.
6369
def f(num1, my_float=3.5):
6470
# type: (int, float) -> float
6571
return num1 + my_float
66-
# This is how you annotate a function value
72+
73+
# This is how you annotate a function value.
6774
x = f # type: Callable[[int, float], float]
6875
69-
# Use Optional[Type] for objects that could be None
70-
def f(input_str=None):
71-
# type: (Optional[str]) -> int
72-
if input_str is not None:
73-
return len(input_str)
74-
return 0
75-
76-
from typing import Mapping, MutableMapping
77-
# Dict is a python dictionary
78-
# MutableMapping is an abstract base class for a dict-type thing
79-
# Mapping is an abtract base class for a dict-type thing that may
80-
# not support writing to the mapping
76+
# A generator function that yields ints is secretly just a function that
77+
# returns an iterable (see below) of ints, so that's how we annotate it.
78+
def f(n):
79+
# type: (int) -> Iterable[int]
80+
i = 0
81+
while i < n:
82+
yield i
83+
i += 1
84+
85+
86+
When you're puzzled or when things are complicated
87+
**************************************************
88+
89+
.. code-block:: python
90+
91+
from typing import Union, Any
92+
93+
# To find out what type mypy infers for an expression anywhere in
94+
# your program, wrap it in reveal_type. Mypy will print an error
95+
# message with the type; remove it again before running the code.
96+
reveal_type(1) # -> error: Revealed type is 'builtins.int'
97+
98+
# Use Union when something could be one of a few types.
99+
x = [3, 5, "test", "fun"] # type: List[Union[int, str]]
100+
101+
# Use Any if you don't know the type of something or it's too
102+
# dynamic to write a type for.
103+
x = mystery_function() # type: Any
104+
105+
# Use `ignore` to suppress type-checking on a given line, when your
106+
# code confuses mypy or runs into an outright bug in mypy.
107+
# Good practice is to comment every `ignore` with a bug link
108+
# (in mypy, typeshed, or your own code) or an explanation of the issue.
109+
x = confusing_function() # type: ignore # https://github.com/python/mypy/issues/1167
110+
111+
# TODO: explain cast
112+
113+
# TODO: explain "Need type annotation for variable" when
114+
# initializing with None or an empty container
115+
116+
117+
Standard duck types
118+
*******************
119+
120+
In typical Python code, many functions that can take a list or a dict
121+
as an argument only need their argument to be somehow "list-like" or
122+
"dict-like". A specific meaning of "list-like" or "dict-like" (or
123+
something-else-like) is called a "duck type", and several duck types
124+
that are common in idiomatic Python are standardized.
125+
126+
.. code-block:: python
127+
128+
from typing import Mapping, MutableMapping, Sequence, Iterator
129+
130+
# Use Iterable for generic iterables (anything usable in `for`),
131+
# and Sequence where a sequence (supporting `len` and `__getitem__`) is required.
132+
def f(iterable_of_ints):
133+
# type: (Iterable[int]) -> List[str]
134+
return [str(x) for x in iterator_of_ints]
135+
f(range(1, 3))
136+
137+
# Mapping describes a dict-like object (with `__getitem__`) that we won't mutate,
138+
# and MutableMapping one (with `__setitem__`) that we might.
81139
def f(my_dict):
82140
# type: (Mapping[int, str]) -> List[int]
83141
return list(my_dict.keys())
84142
f({3: 'yes', 4: 'no'})
85-
86143
def f(my_mapping):
87144
# type: (MutableMapping[int, str]) -> Set[str]
88145
my_dict[5] = 'maybe'
89146
return set(my_dict.values())
90147
f({3: 'yes', 4: 'no'})
91148
92-
from typing import Sequence, Iterable, Generator
93-
# Use Iterable[Type] for generic iterators
94-
# Sequence[Type] is abstract base class for list-like iterables
95-
def f(iterator_of_ints):
96-
# type: (Sequence[int]) -> List[str]
97-
return [str(x) for x in iterator_of_ints]
98-
f(range(1, 3))
99-
100-
from typing import Tuple
101-
def f(my_tuple):
102-
# type: (Tuple[int, int]) -> int
103-
return sum([val for val in my_tuple])
104-
f((1, 2))
105149
106-
from typing import Iterator
107-
def f(n):
108-
# type: (int) -> Iterator[int]
109-
i = 0
110-
while i < n:
111-
yield i
112-
i += 1
113-
f(5)
150+
Classes
151+
*******
114152

115-
# TODO: Add typevar example
153+
.. code-block:: python
116154
117-
# This is how you annotate a class with '__init__' constructor and a method.
118155
class MyClass(object):
119-
"""This is where your class docstring goes."""
120-
121-
def __init__(self):
122-
# type: () -> None
123-
"""Add your constructor stuff here."""
124-
pass
125156
157+
# For instance methods, omit `self`.
126158
def my_class_method(self, num, str1):
127159
# type: (int, str) -> str
128-
"""Returns 'str1' repeated 'num' times."""
129160
return num * str1
130161
162+
# The __init__ method doesn't return anything, so it gets return
163+
# type None just like any other method that doesn't return anything.
164+
def __init__(self):
165+
# type: () -> None
166+
pass
167+
168+
# User-defined classes are written with just their own names.
131169
x = MyClass() # type: MyClass
170+
171+
172+
Other stuff
173+
***********
174+
175+
.. code-block:: python
176+
177+
# typing.Match describes regex matches from the re module.
178+
from typing import Match
179+
x = re.match(r'[0-9]+', "15") # type: Match[str]
180+
181+
# TODO: add typing.IO: e.g., sys.stdout has type IO[str]
182+
183+
# TODO: add TypeVar and a simple generic function
184+
185+
# TODO: add AnyStr (and mention up next to strings)

0 commit comments

Comments
 (0)