@@ -20,8 +20,9 @@ The function below takes and returns a string and is annotated as follows::
20
20
def greeting(name: str) -> str:
21
21
return 'Hello ' + name
22
22
23
- In the function `greeting `, the argument `name ` is expected to by of type `str `
24
- and the return type `str `. Subtypes are accepted as arguments.
23
+ In the function ``greeting ``, the argument ``name `` is expected to by of type
24
+ :class: `str ` and the return type :class: `str `. Subtypes are accepted as
25
+ arguments.
25
26
26
27
Type aliases
27
28
------------
@@ -49,8 +50,8 @@ For example::
49
50
50
51
It is possible to declare the return type of a callable without specifying
51
52
the call signature by substituting a literal ellipsis
52
- for the list of arguments in the type hint: `Callable[..., ReturnType] `.
53
- `None ` as a type hint is a special case and is replaced by `type(None) `.
53
+ for the list of arguments in the type hint: `` Callable[..., ReturnType] ` `.
54
+ `` None `` as a type hint is a special case and is replaced by `` type(None) ` `.
54
55
55
56
Generics
56
57
--------
@@ -67,7 +68,7 @@ subscription to denote expected types for container elements.
67
68
overrides : Mapping[str , str ]) -> None : ...
68
69
69
70
Generics can be parametrized by using a new factory available in typing
70
- called TypeVar.
71
+ called :class: ` TypeVar ` .
71
72
72
73
.. code-block :: python
73
74
@@ -108,11 +109,12 @@ A user-defined class can be defined as a generic class.
108
109
def log (self , message : str ) -> None :
109
110
self .logger.info(' {} : {} ' .format(self .name, message))
110
111
111
- `Generic[T] ` as a base class defines that the class `LoggedVar ` takes a single
112
- type parameter `T ` . This also makes `T ` valid as a type within the class body.
112
+ ``Generic[T] `` as a base class defines that the class ``LoggedVar `` takes a
113
+ single type parameter ``T `` . This also makes ``T `` valid as a type within the
114
+ class body.
113
115
114
- The `Generic ` base class uses a metaclass that defines ` __getitem__ ` so that
115
- ` LoggedVar[t] ` is valid as a type::
116
+ The :class: `Generic ` base class uses a metaclass that defines
117
+ :meth: ` __getitem__ ` so that `` LoggedVar[t] ` ` is valid as a type::
116
118
117
119
from typing import Iterable
118
120
@@ -132,7 +134,7 @@ be constrained::
132
134
class StrangePair(Generic[T, S]):
133
135
...
134
136
135
- Each type variable argument to `Generic ` must be distinct.
137
+ Each type variable argument to :class: `Generic ` must be distinct.
136
138
This is thus invalid::
137
139
138
140
from typing import TypeVar, Generic
@@ -143,7 +145,7 @@ This is thus invalid::
143
145
class Pair(Generic[T, T]): # INVALID
144
146
...
145
147
146
- You can use multiple inheritance with `Generic `::
148
+ You can use multiple inheritance with :class: `Generic `::
147
149
148
150
from typing import TypeVar, Generic, Sized
149
151
@@ -152,38 +154,44 @@ You can use multiple inheritance with `Generic`::
152
154
class LinkedList(Sized, Generic[T]):
153
155
...
154
156
155
- Subclassing a generic class without specifying type parameters assumes `Any `
156
- for each position. In the following example, `MyIterable ` is not generic but
157
- implicitly inherits from `Iterable[Any] `::
157
+ When inheriting from generic classes, some type variables could fixed::
158
158
159
- from typing import Iterable
159
+ from typing import TypeVar, Mapping
160
160
161
- class MyIterable(Iterable): # Same as Iterable[Any]
161
+ T = TypeVar('T')
162
162
163
- Generic metaclasses are not supported.
163
+ class MyDict(Mapping[str, T]):
164
+ ...
164
165
165
- The `Any ` type
166
- --------------
166
+ In this case ``MyDict `` has a single parameter, ``T ``.
167
+
168
+ Subclassing a generic class without specifying type parameters assumes
169
+ :class: `Any ` for each position. In the following example, ``MyIterable `` is
170
+ not generic but implicitly inherits from ``Iterable[Any] ``::
171
+
172
+ from typing import Iterable
167
173
168
- A special kind of type is `Any `. Every type is a subtype of `Any `.
169
- This is also true for the builtin type object. However, to the static type
170
- checker these are completely different.
174
+ class MyIterable(Iterable): # Same as Iterable[Any]
171
175
172
- When the type of a value is `object `, the type checker will reject almost all
173
- operations on it, and assigning it to a variable (or using it as a return value)
174
- of a more specialized type is a type error. On the other hand, when a value has
175
- type `Any `, the type checker will allow all operations on it, and a value of
176
- type `Any ` can be assigned to a variable (or used as a return value) of a more
177
- constrained type.
176
+ The metaclass used by :class: `Generic ` is a subclass of :class: `abc.ABCMeta `.
177
+ A generic class can be an ABC by including abstract methods or properties,
178
+ and generic classes can also have ABCs as base classes without a metaclass
179
+ conflict. Generic metaclasses are not supported.
178
180
179
- Default argument values
180
- -----------------------
181
181
182
- Use a literal ellipsis `... ` to declare an argument as having a default value::
182
+ The :class: `Any ` type
183
+ ---------------------
183
184
184
- from typing import AnyStr
185
+ A special kind of type is :class: `Any `. Every type is a subtype of
186
+ :class: `Any `. This is also true for the builtin type object. However, to the
187
+ static type checker these are completely different.
185
188
186
- def foo(x: AnyStr, y: AnyStr = ...) -> AnyStr: ...
189
+ When the type of a value is :class: `object `, the type checker will reject
190
+ almost all operations on it, and assigning it to a variable (or using it as a
191
+ return value) of a more specialized type is a type error. On the other hand,
192
+ when a value has type :class: `Any `, the type checker will allow all operations
193
+ on it, and a value of type :class: `Any ` can be assigned to a variable (or used
194
+ as a return value) of a more constrained type.
187
195
188
196
189
197
Classes, functions, and decorators
@@ -195,9 +203,10 @@ The module defines the following classes, functions and decorators:
195
203
196
204
Special type indicating an unconstrained type.
197
205
198
- * Any object is an instance of `Any `.
199
- * Any class is a subclass of `Any `.
200
- * As a special case, `Any ` and `object ` are subclasses of each other.
206
+ * Any object is an instance of :class: `Any `.
207
+ * Any class is a subclass of :class: `Any `.
208
+ * As a special case, :class: `Any ` and :class: `object ` are subclasses of
209
+ each other.
201
210
202
211
.. class :: TypeVar
203
212
@@ -224,22 +233,26 @@ The module defines the following classes, functions and decorators:
224
233
return x if len (x) >= len (y) else y
225
234
226
235
The latter example's signature is essentially the overloading
227
- of `(str, str) -> str ` and `(bytes, bytes) -> bytes `. Also note
228
- that if the arguments are instances of some subclass of `str `,
229
- the return type is still plain `str `.
236
+ of `` (str, str) -> str `` and `` (bytes, bytes) -> bytes ` `. Also note
237
+ that if the arguments are instances of some subclass of :class: `str `,
238
+ the return type is still plain :class: `str `.
230
239
231
- At runtime, `isinstance(x, T) ` will raise `TypeError `. In general,
232
- `isinstance ` and `issublass ` should not be used with types.
240
+ At runtime, `` isinstance(x, T) `` will raise :exc: `TypeError `. In general,
241
+ :func: `isinstance ` and :func: `issublass ` should not be used with types.
233
242
234
243
Type variables may be marked covariant or contravariant by passing
235
- `covariant=True ` or `contravariant=True `. See :pep: `484 ` for more
236
- details. By default type variables are invariant.
244
+ ``covariant=True `` or ``contravariant=True ``. See :pep: `484 ` for more
245
+ details. By default type variables are invariant. Alternatively,
246
+ a type variable may specify an upper bound using ``bound=<type> ``.
247
+ This means that an actual type substituted (explicitly or implictly)
248
+ for the type variable must be a subclass of the boundary type,
249
+ see :pep: `484 `.
237
250
238
251
.. class :: Union
239
252
240
- Union type; `Union[X, Y] ` means either X or Y.
253
+ Union type; `` Union[X, Y] ` ` means either X or Y.
241
254
242
- To define a union, use e.g. `Union[int, str] `. Details:
255
+ To define a union, use e.g. `` Union[int, str] ` `. Details:
243
256
244
257
* The arguments must be types and there must be at least one.
245
258
@@ -259,47 +272,47 @@ The module defines the following classes, functions and decorators:
259
272
260
273
Union[int, str] == Union[str, int]
261
274
262
- * If `Any ` is present it is the sole survivor, e.g.::
275
+ * If :class: `Any ` is present it is the sole survivor, e.g.::
263
276
264
277
Union[int, Any] == Any
265
278
266
279
* You cannot subclass or instantiate a union.
267
280
268
- * You cannot write `Union[X][Y] `
281
+ * You cannot write `` Union[X][Y] ` `
269
282
270
- * You can use `Optional[X] ` as a shorthand for `Union[X, None] `.
283
+ * You can use `` Optional[X] `` as a shorthand for `` Union[X, None] ` `.
271
284
272
285
.. class :: Optional
273
286
274
287
Optional type.
275
288
276
- `Optional[X] ` is equivalent to `Union[X, type(None)] `.
289
+ `` Optional[X] `` is equivalent to `` Union[X, type(None)] ` `.
277
290
278
291
.. class :: Tuple
279
292
280
- Tuple type; `Tuple[X, Y] ` is the is the type of a tuple of two items
293
+ Tuple type; `` Tuple[X, Y] ` ` is the is the type of a tuple of two items
281
294
with the first item of type X and the second of type Y.
282
295
283
- Example: `Tuple[T1, T2] ` is a tuple of two elements corresponding
284
- to type variables T1 and T2. `Tuple[int, float, str] ` is a tuple
296
+ Example: `` Tuple[T1, T2] ` ` is a tuple of two elements corresponding
297
+ to type variables T1 and T2. `` Tuple[int, float, str] ` ` is a tuple
285
298
of an int, a float and a string.
286
299
287
300
To specify a variable-length tuple of homogeneous type,
288
- use literal ellipsis, e.g. `Tuple[int, ...] `.
301
+ use literal ellipsis, e.g. `` Tuple[int, ...] ` `.
289
302
290
303
.. class :: Callable
291
304
292
- Callable type; `Callable[[int], str] ` is a function of (int) -> str.
305
+ Callable type; `` Callable[[int], str] ` ` is a function of (int) -> str.
293
306
294
307
The subscription syntax must always be used with exactly two
295
308
values: the argument list and the return type. The argument list
296
309
must be a list of types; the return type must be a single type.
297
310
298
311
There is no syntax to indicate optional or keyword arguments,
299
312
such function types are rarely used as callback types.
300
- `Callable[..., ReturnType] ` could be used to type hint a callable
301
- taking any number of arguments and returning `ReturnType `.
302
- A plain `Callable ` is equivalent to `Callable[..., Any] `.
313
+ `` Callable[..., ReturnType] ` ` could be used to type hint a callable
314
+ taking any number of arguments and returning `` ReturnType ` `.
315
+ A plain :class: `Callable ` is equivalent to `` Callable[..., Any] ` `.
303
316
304
317
.. class :: Generic
305
318
@@ -326,57 +339,139 @@ The module defines the following classes, functions and decorators:
326
339
327
340
.. class :: Iterable(Generic[T_co])
328
341
342
+ A generic version of the :class: `collections.abc.Iterable `.
343
+
329
344
.. class :: Iterator(Iterable[T_co])
330
345
346
+ A generic version of the :class: `collections.abc.Iterator `.
347
+
331
348
.. class :: SupportsInt
332
349
350
+ An ABC with one abstract method `__int__ `.
351
+
333
352
.. class :: SupportsFloat
334
353
354
+ An ABC with one abstract method `__float__ `.
355
+
335
356
.. class :: SupportsAbs
336
357
358
+ An ABC with one abstract method `__abs__ ` that is covariant
359
+ in its return type.
360
+
337
361
.. class :: SupportsRound
338
362
363
+ An ABC with one abstract method `__round__ `
364
+ that is covariant in its return type.
365
+
339
366
.. class :: Reversible
340
367
368
+ An ABC with one abstract method `__reversed__ ` returning
369
+ an `Iterator[T_co] `.
370
+
341
371
.. class :: Container(Generic[T_co])
342
372
373
+ A generic version of :class: `collections.abc.Container `.
374
+
343
375
.. class :: AbstractSet(Sized, Iterable[T_co], Container[T_co])
344
376
377
+ A generic version of :class: `collections.abc.Set `.
378
+
345
379
.. class :: MutableSet(AbstractSet[T])
346
380
347
- .. class :: Mapping(Sized, Iterable[KT_co], Container[KT_co], Generic[KT_co, VT_co])
381
+ A generic version of :class: `collections.abc.MutableSet `.
382
+
383
+ .. class :: Mapping(Sized, Iterable[KT], Container[KT], Generic[VT_co])
384
+
385
+ A generic version of :class: `collections.abc.Mapping `.
348
386
349
387
.. class :: MutableMapping(Mapping[KT, VT])
350
388
389
+ A generic version of :class: `collections.abc.MutableMapping `.
390
+
351
391
.. class :: Sequence(Sized, Iterable[T_co], Container[T_co])
352
392
393
+ A generic version of :class: `collections.abc.Sequence `.
394
+
353
395
.. class :: MutableSequence(Sequence[T])
354
396
397
+ A generic version of :class: `collections.abc.MutableSequence `.
398
+
355
399
.. class :: ByteString(Sequence[int])
356
400
401
+ A generic version of :class: `collections.abc.ByteString `.
402
+
403
+ This type represents the types :class: `bytes `, :class: `bytearray `,
404
+ and :class: `memoryview `.
405
+
406
+ As a shorthand for this type, :class: `bytes ` can be used to
407
+ annotate arguments of any of the types mentioned above.
408
+
357
409
.. class :: List(list, MutableSequence[T])
358
410
359
- .. class :: Set(set, MutableSet[T])
411
+ Generic version of :class: `list `.
412
+ Useful for annotating return types. To annotate arguments it is preferred
413
+ to use abstract collection types such as :class: `Mapping `, :class: `Sequence `,
414
+ or :class: `AbstractSet `.
415
+
416
+ This type may be used as follows::
417
+
418
+ T = TypeVar('T', int, float)
419
+
420
+ def vec2(x: T, y: T) -> List[T]:
421
+ return [x, y]
422
+
423
+ def slice__to_4(vector: Sequence[T]) -> List[T]:
424
+ return vector[0:4]
425
+
426
+ .. class :: AbstractSet(set, MutableSet[T])
427
+
428
+ A generic version of :class: `collections.abc.Set `.
360
429
361
430
.. class :: MappingView(Sized, Iterable[T_co])
362
431
432
+ A generic version of :class: `collections.abc.MappingView `.
433
+
363
434
.. class :: KeysView(MappingView[KT_co], AbstractSet[KT_co])
364
435
436
+ A generic version of :class: `collections.abc.KeysView `.
437
+
365
438
.. class :: ItemsView(MappingView, Generic[KT_co, VT_co])
366
439
440
+ A generic version of :class: `collections.abc.ItemsView `.
441
+
367
442
.. class :: ValuesView(MappingView[VT_co])
368
443
444
+ A generic version of :class: `collections.abc.ValuesView `.
445
+
369
446
.. class :: Dict(dict, MutableMapping[KT, VT])
370
447
448
+ A generic version of :class: `dict `.
449
+ The usage of this type is as follows::
450
+
451
+ def get_position_in_index(word_list: Dict[str, int], word: str) -> int:
452
+ return word_list[word]
453
+
371
454
.. class :: Generator(Iterator[T_co], Generic[T_co, T_contra, V_co])
372
455
373
456
.. class :: io
374
457
375
- Wrapper namespace for IO generic classes.
458
+ Wrapper namespace for I/O stream types.
459
+
460
+ This defines the generic type ``IO[AnyStr] `` and aliases ``TextIO ``
461
+ and ``BinaryIO `` for respectively ``IO[str] `` and ``IO[bytes] ``.
462
+ These representing the types of I/O streams such as returned by
463
+ :func: `open `.
376
464
377
465
.. class :: re
378
466
379
- Wrapper namespace for re type classes.
467
+ Wrapper namespace for regular expression matching types.
468
+
469
+ This defines the type aliases ``Pattern `` and ``Match `` which
470
+ correspond to the return types from :func: `re.compile ` and
471
+ :func: `re.match `. These types (and the corresponding functions)
472
+ are generic in ``AnyStr `` and can be made specific by writing
473
+ ``Pattern[str] ``, ``Pattern[bytes] ``, ``Match[str] ``, or
474
+ ``Match[bytes] ``.
380
475
381
476
.. function :: NamedTuple(typename, fields)
382
477
0 commit comments