Debian Codegraph @

docs/source/cheat_sheet_py3.rst

raw
1 .. _cheat-sheet-py3:
2
3 Type hints cheat sheet
4 ======================
5
6 This document is a quick cheat sheet showing how to use type
7 annotations for various common types in Python.
8
9 Variables
10 *********
11
12 Technically many of the type annotations shown below are redundant,
13 since mypy can usually infer the type of a variable from its value.
14 See :ref:`type-inference-and-annotations` for more details.
15
16 .. code-block:: python
17
18 # This is how you declare the type of a variable
19 age: int = 1
20
21 # You don't need to initialize a variable to annotate it
22 a: int # Ok (no value at runtime until assigned)
23
24 # Doing so can be useful in conditional branches
25 child: bool
26 if age < 18:
27 child = True
28 else:
29 child = False
30
31
32 Useful built-in types
33 *********************
34
35 .. code-block:: python
36
37 # For most types, just use the name of the type in the annotation
38 # Note that mypy can usually infer the type of a variable from its value,
39 # so technically these annotations are redundant
40 x: int = 1
41 x: float = 1.0
42 x: bool = True
43 x: str = "test"
44 x: bytes = b"test"
45
46 # For collections, the type of the collection item is in brackets
47 x: list[int] = [1]
48 x: set[int] = {6, 7}
49
50 # For mappings, we need the types of both keys and values
51 x: dict[str, float] = {"field": 2.0}
52
53 # For tuples of fixed size, we specify the types of all the elements
54 x: tuple[int, str, float] = (3, "yes", 7.5)
55
56 # For tuples of variable size, we use one type and ellipsis
57 x: tuple[int, ...] = (1, 2, 3)
58
59 # On Python 3.8 and earlier, the name of the collection type is
60 # capitalized, and the type is imported from the 'typing' module
61 from typing import List, Set, Dict, Tuple
62 x: List[int] = [1]
63 x: Set[int] = {6, 7}
64 x: Dict[str, float] = {"field": 2.0}
65 x: Tuple[int, str, float] = (3, "yes", 7.5)
66 x: Tuple[int, ...] = (1, 2, 3)
67
68 from typing import Union, Optional
69
70 # Use the | operator when something could be one of a few types
71 x: list[int | str] = [3, 5, "test", "fun"]
72 # Union is equivalent
73 x: list[Union[int, str]] = [3, 5, "test", "fun"]
74
75 # Use X | None for a value that could be None; Optional[X] is the same as X | None
76 x: str | None = "something" if some_condition() else None
77 if x is not None:
78 # Mypy understands x won't be None here because of the if-statement
79 print(x.upper())
80 # If you know a value can never be None due to some logic that mypy doesn't
81 # understand, use an assert
82 assert x is not None
83 print(x.upper())
84
85 Functions
86 *********
87
88 .. code-block:: python
89
90 from collections.abc import Iterator, Callable
91 from typing import Union, Optional
92
93 # This is how you annotate a function definition
94 def stringify(num: int) -> str:
95 return str(num)
96
97 # And here's how you specify multiple arguments
98 def plus(num1: int, num2: int) -> int:
99 return num1 + num2
100
101 # If a function does not return a value, use None as the return type
102 # Default value for an argument goes after the type annotation
103 def show(value: str, excitement: int = 10) -> None:
104 print(value + "!" * excitement)
105
106 # Note that arguments without a type are dynamically typed (treated as Any)
107 # and that functions without any annotations are not checked
108 def untyped(x):
109 x.anything() + 1 + "string" # no errors
110
111 # This is how you annotate a callable (function) value
112 x: Callable[[int, float], float] = f
113 def register(callback: Callable[[str], int]) -> None: ...
114
115 # A generator function that yields ints is secretly just a function that
116 # returns an iterator of ints, so that's how we annotate it
117 def gen(n: int) -> Iterator[int]:
118 i = 0
119 while i < n:
120 yield i
121 i += 1
122
123 # You can of course split a function annotation over multiple lines
124 def send_email(
125 address: str | list[str],
126 sender: str,
127 cc: list[str] | None,
128 bcc: list[str] | None,
129 subject: str = '',
130 body: list[str] | None = None,
131 ) -> bool:
132 ...
133
134 # Mypy understands positional-only and keyword-only arguments
135 # Positional-only arguments can also be marked by using a name starting with
136 # two underscores
137 def quux(x: int, /, *, y: int) -> None:
138 pass
139
140 quux(3, y=5) # Ok
141 quux(3, 5) # error: Too many positional arguments for "quux"
142 quux(x=3, y=5) # error: Unexpected keyword argument "x" for "quux"
143
144 # This says each positional arg and each keyword arg is a "str"
145 def call(self, *args: str, **kwargs: str) -> str:
146 reveal_type(args) # Revealed type is "tuple[str, ...]"
147 reveal_type(kwargs) # Revealed type is "dict[str, str]"
148 request = make_request(*args, **kwargs)
149 return self.do_api_query(request)
150
151 Classes
152 *******
153
154 .. code-block:: python
155
156 from typing import ClassVar
157
158 class BankAccount:
159 # The "__init__" method doesn't return anything, so it gets return
160 # type "None" just like any other method that doesn't return anything
161 def __init__(self, account_name: str, initial_balance: int = 0) -> None:
162 # mypy will infer the correct types for these instance variables
163 # based on the types of the parameters.
164 self.account_name = account_name
165 self.balance = initial_balance
166
167 # For instance methods, omit type for "self"
168 def deposit(self, amount: int) -> None:
169 self.balance += amount
170
171 def withdraw(self, amount: int) -> None:
172 self.balance -= amount
173
174 # User-defined classes are valid as types in annotations
175 account: BankAccount = BankAccount("Alice", 400)
176 def transfer(src: BankAccount, dst: BankAccount, amount: int) -> None:
177 src.withdraw(amount)
178 dst.deposit(amount)
179
180 # Functions that accept BankAccount also accept any subclass of BankAccount!
181 class AuditedBankAccount(BankAccount):
182 # You can optionally declare instance variables in the class body
183 audit_log: list[str]
184
185 def __init__(self, account_name: str, initial_balance: int = 0) -> None:
186 super().__init__(account_name, initial_balance)
187 self.audit_log: list[str] = []
188
189 def deposit(self, amount: int) -> None:
190 self.audit_log.append(f"Deposited {amount}")
191 self.balance += amount
192
193 def withdraw(self, amount: int) -> None:
194 self.audit_log.append(f"Withdrew {amount}")
195 self.balance -= amount
196
197 audited = AuditedBankAccount("Bob", 300)
198 transfer(audited, account, 100) # type checks!
199
200 # You can use the ClassVar annotation to declare a class variable
201 class Car:
202 seats: ClassVar[int] = 4
203 passengers: ClassVar[list[str]]
204
205 # If you want dynamic attributes on your class, have it
206 # override "__setattr__" or "__getattr__"
207 class A:
208 # This will allow assignment to any A.x, if x is the same type as "value"
209 # (use "value: Any" to allow arbitrary types)
210 def __setattr__(self, name: str, value: int) -> None: ...
211
212 # This will allow access to any A.x, if x is compatible with the return type
213 def __getattr__(self, name: str) -> int: ...
214
215 a = A()
216 a.foo = 42 # Works
217 a.bar = 'Ex-parrot' # Fails type checking
218
219 When you're puzzled or when things are complicated
220 **************************************************
221
222 .. code-block:: python
223
224 from typing import Union, Any, Optional, TYPE_CHECKING, cast
225
226 # To find out what type mypy infers for an expression anywhere in
227 # your program, wrap it in reveal_type(). Mypy will print an error
228 # message with the type; remove it again before running the code.
229 reveal_type(1) # Revealed type is "builtins.int"
230
231 # If you initialize a variable with an empty container or "None"
232 # you may have to help mypy a bit by providing an explicit type annotation
233 x: list[str] = []
234 x: str | None = None
235
236 # Use Any if you don't know the type of something or it's too
237 # dynamic to write a type for
238 x: Any = mystery_function()
239 # Mypy will let you do anything with x!
240 x.whatever() * x["you"] + x("want") - any(x) and all(x) is super # no errors
241
242 # Use a "type: ignore" comment to suppress errors on a given line,
243 # when your code confuses mypy or runs into an outright bug in mypy.
244 # Good practice is to add a comment explaining the issue.
245 x = confusing_function() # type: ignore # confusing_function won't return None here because ...
246
247 # "cast" is a helper function that lets you override the inferred
248 # type of an expression. It's only for mypy -- there's no runtime check.
249 a = [4]
250 b = cast(list[int], a) # Passes fine
251 c = cast(list[str], a) # Passes fine despite being a lie (no runtime check)
252 reveal_type(c) # Revealed type is "builtins.list[builtins.str]"
253 print(c) # Still prints [4] ... the object is not changed or casted at runtime
254
255 # Use "TYPE_CHECKING" if you want to have code that mypy can see but will not
256 # be executed at runtime (or to have code that mypy can't see)
257 if TYPE_CHECKING:
258 import json
259 else:
260 import orjson as json # mypy is unaware of this
261
262 In some cases type annotations can cause issues at runtime, see
263 :ref:`runtime_troubles` for dealing with this.
264
265 See :ref:`silencing-type-errors` for details on how to silence errors.
266
267 Standard "duck types"
268 *********************
269
270 In typical Python code, many functions that can take a list or a dict
271 as an argument only need their argument to be somehow "list-like" or
272 "dict-like". A specific meaning of "list-like" or "dict-like" (or
273 something-else-like) is called a "duck type", and several duck types
274 that are common in idiomatic Python are standardized.
275
276 .. code-block:: python
277
278 from collections.abc import Mapping, MutableMapping, Sequence, Iterable
279 # or 'from typing import ...' (required in Python 3.8)
280
281 # Use Iterable for generic iterables (anything usable in "for"),
282 # and Sequence where a sequence (supporting "len" and "__getitem__") is
283 # required
284 def f(ints: Iterable[int]) -> list[str]:
285 return [str(x) for x in ints]
286
287 f(range(1, 3))
288
289 # Mapping describes a dict-like object (with "__getitem__") that we won't
290 # mutate, and MutableMapping one (with "__setitem__") that we might
291 def f(my_mapping: Mapping[int, str]) -> list[int]:
292 my_mapping[5] = 'maybe' # mypy will complain about this line...
293 return list(my_mapping.keys())
294
295 f({3: 'yes', 4: 'no'})
296
297 def f(my_mapping: MutableMapping[int, str]) -> set[str]:
298 my_mapping[5] = 'maybe' # ...but mypy is OK with this.
299 return set(my_mapping.values())
300
301 f({3: 'yes', 4: 'no'})
302
303 import sys
304 from typing import IO
305
306 # Use IO[str] or IO[bytes] for functions that should accept or return
307 # objects that come from an open() call (note that IO does not
308 # distinguish between reading, writing or other modes)
309 def get_sys_IO(mode: str = 'w') -> IO[str]:
310 if mode == 'w':
311 return sys.stdout
312 elif mode == 'r':
313 return sys.stdin
314 else:
315 return sys.stdout
316
317
318 You can even make your own duck types using :ref:`protocol-types`.
319
320 Forward references
321 ******************
322
323 .. code-block:: python
324
325 # You may want to reference a class before it is defined.
326 # This is known as a "forward reference".
327 def f(foo: A) -> int: # This will fail at runtime with 'A' is not defined
328 ...
329
330 # However, if you add the following special import:
331 from __future__ import annotations
332 # It will work at runtime and type checking will succeed as long as there
333 # is a class of that name later on in the file
334 def f(foo: A) -> int: # Ok
335 ...
336
337 # Another option is to just put the type in quotes
338 def f(foo: 'A') -> int: # Also ok
339 ...
340
341 class A:
342 # This can also come up if you need to reference a class in a type
343 # annotation inside the definition of that class
344 @classmethod
345 def create(cls) -> A:
346 ...
347
348 See :ref:`forward-references` for more details.
349
350 Decorators
351 **********
352
353 Decorator functions can be expressed via generics. See
354 :ref:`declaring-decorators` for more details. Example using Python 3.12
355 syntax:
356
357 .. code-block:: python
358
359 from collections.abc import Callable
360 from typing import Any
361
362 def bare_decorator[F: Callable[..., Any]](func: F) -> F:
363 ...
364
365 def decorator_args[F: Callable[..., Any]](url: str) -> Callable[[F], F]:
366 ...
367
368 The same example using pre-3.12 syntax:
369
370 .. code-block:: python
371
372 from collections.abc import Callable
373 from typing import Any, TypeVar
374
375 F = TypeVar('F', bound=Callable[..., Any])
376
377 def bare_decorator(func: F) -> F:
378 ...
379
380 def decorator_args(url: str) -> Callable[[F], F]:
381 ...
382
383 Coroutines and asyncio
384 **********************
385
386 See :ref:`async-and-await` for the full detail on typing coroutines and asynchronous code.
387
388 .. code-block:: python
389
390 import asyncio
391
392 # A coroutine is typed like a normal function
393 async def countdown(tag: str, count: int) -> str:
394 while count > 0:
395 print(f'T-minus {count} ({tag})')
396 await asyncio.sleep(0.1)
397 count -= 1
398 return "Blastoff!"