1
1
Mypy syntax cheat sheet (Python 2)
2
2
==================================
3
3
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
5
5
language represents various common types in Python 2.
6
6
7
7
.. note ::
@@ -11,121 +11,175 @@ language represents various common types in Python 2.
11
11
many of the examples have a dual purpose: show how to write the
12
12
annotation, and show the inferred types.
13
13
14
+
15
+ Built-in types
16
+ **************
17
+
14
18
.. code-block :: python
15
19
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
18
22
19
- # For builtin types, just use the name of the type
23
+ # For simple built-in types, just use the name of the type.
20
24
x = 1 # type: int
21
25
x = 1.0 # type: float
22
26
x = " test" # type: str
23
27
x = u " test" # type: unicode
24
28
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
-
29
29
# 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.
31
31
x = [1 ] # type: List [ int ]
32
32
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.
34
35
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.
36
38
x = (3 , " yes" , 7.5 ) # type: Tuple [ int , str , float ]
37
39
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
43
48
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
50
49
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.
52
58
def stringify (num ):
53
59
# type: ( int ) -> str
54
60
""" Your function docstring goes here after the type definition."""
55
61
return str (num)
56
62
57
- # And here's how you specify multiple arguments
63
+ # And here's how you specify multiple arguments.
58
64
def plus (num1 , num2 ):
59
65
# type: ( int , int ) -> int
60
66
return num1 + num2
61
67
62
- # Add type annotations for kwargs as though they were positional args
68
+ # Add type annotations for kwargs as though they were positional args.
63
69
def f (num1 , my_float = 3.5 ):
64
70
# type: ( int , float ) -> float
65
71
return num1 + my_float
66
- # This is how you annotate a function value
72
+
73
+ # This is how you annotate a function value.
67
74
x = f # type: Callable [[ int , float ], float ]
68
75
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.
81
139
def f (my_dict ):
82
140
# type: ( Mapping [ int , str ]) -> List [ int ]
83
141
return list (my_dict.keys())
84
142
f({3 : ' yes' , 4 : ' no' })
85
-
86
143
def f (my_mapping ):
87
144
# type: ( MutableMapping [ int , str ]) -> Set [ str ]
88
145
my_dict[5 ] = ' maybe'
89
146
return set (my_dict.values())
90
147
f({3 : ' yes' , 4 : ' no' })
91
148
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 ))
105
149
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
+ *******
114
152
115
- # TODO : Add typevar example
153
+ .. code-block :: python
116
154
117
- # This is how you annotate a class with '__init__' constructor and a method.
118
155
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
125
156
157
+ # For instance methods, omit `self`.
126
158
def my_class_method (self , num , str1 ):
127
159
# type: ( int , str ) -> str
128
- """ Returns 'str1' repeated 'num' times."""
129
160
return num * str1
130
161
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.
131
169
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