Skip to content
This repository was archived by the owner on Feb 13, 2025. It is now read-only.

Commit 470e792

Browse files
author
Anselm Kruis
committed
merge branch 3.5 just after tagging v3.5.0
2 parents c689ab1 + 1f9f61c commit 470e792

File tree

8 files changed

+14380
-695
lines changed

8 files changed

+14380
-695
lines changed

.hgtags

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -177,3 +177,4 @@ c0d64105463581f85d0e368e8d6e59b7fd8f12b1 v3.5.0b4
177177
cc15d736d860303b9da90d43cd32db39bab048df v3.5.0rc2
178178
66ed52375df802f9d0a34480daaa8ce79fc41313 v3.5.0rc3
179179
2d033fedfa7f1e325fd14ccdaa9cb42155da206f v3.5.0rc4
180+
374f501f4567b7595f2ad7798aa09afa2456bb28 v3.5.0

Doc/library/typing.rst

Lines changed: 156 additions & 61 deletions
Original file line numberDiff line numberDiff line change
@@ -20,8 +20,9 @@ The function below takes and returns a string and is annotated as follows::
2020
def greeting(name: str) -> str:
2121
return 'Hello ' + name
2222

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.
2526

2627
Type aliases
2728
------------
@@ -49,8 +50,8 @@ For example::
4950

5051
It is possible to declare the return type of a callable without specifying
5152
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)``.
5455

5556
Generics
5657
--------
@@ -67,7 +68,7 @@ subscription to denote expected types for container elements.
6768
overrides: Mapping[str, str]) -> None: ...
6869
6970
Generics can be parametrized by using a new factory available in typing
70-
called TypeVar.
71+
called :class:`TypeVar`.
7172

7273
.. code-block:: python
7374
@@ -108,11 +109,12 @@ A user-defined class can be defined as a generic class.
108109
def log(self, message: str) -> None:
109110
self.logger.info('{}: {}'.format(self.name, message))
110111
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.
113115

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::
116118

117119
from typing import Iterable
118120

@@ -132,7 +134,7 @@ be constrained::
132134
class StrangePair(Generic[T, S]):
133135
...
134136

135-
Each type variable argument to `Generic` must be distinct.
137+
Each type variable argument to :class:`Generic` must be distinct.
136138
This is thus invalid::
137139

138140
from typing import TypeVar, Generic
@@ -143,7 +145,7 @@ This is thus invalid::
143145
class Pair(Generic[T, T]): # INVALID
144146
...
145147

146-
You can use multiple inheritance with `Generic`::
148+
You can use multiple inheritance with :class:`Generic`::
147149

148150
from typing import TypeVar, Generic, Sized
149151

@@ -152,38 +154,44 @@ You can use multiple inheritance with `Generic`::
152154
class LinkedList(Sized, Generic[T]):
153155
...
154156

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::
158158

159-
from typing import Iterable
159+
from typing import TypeVar, Mapping
160160

161-
class MyIterable(Iterable): # Same as Iterable[Any]
161+
T = TypeVar('T')
162162

163-
Generic metaclasses are not supported.
163+
class MyDict(Mapping[str, T]):
164+
...
164165

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
167173

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]
171175

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.
178180

179-
Default argument values
180-
-----------------------
181181

182-
Use a literal ellipsis `...` to declare an argument as having a default value::
182+
The :class:`Any` type
183+
---------------------
183184

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.
185188

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.
187195

188196

189197
Classes, functions, and decorators
@@ -195,9 +203,10 @@ The module defines the following classes, functions and decorators:
195203

196204
Special type indicating an unconstrained type.
197205

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.
201210

202211
.. class:: TypeVar
203212

@@ -224,22 +233,26 @@ The module defines the following classes, functions and decorators:
224233
return x if len(x) >= len(y) else y
225234
226235
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`.
230239

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.
233242

234243
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`.
237250

238251
.. class:: Union
239252

240-
Union type; `Union[X, Y]` means either X or Y.
253+
Union type; ``Union[X, Y]`` means either X or Y.
241254

242-
To define a union, use e.g. `Union[int, str]`. Details:
255+
To define a union, use e.g. ``Union[int, str]``. Details:
243256

244257
* The arguments must be types and there must be at least one.
245258

@@ -259,47 +272,47 @@ The module defines the following classes, functions and decorators:
259272

260273
Union[int, str] == Union[str, int]
261274

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.::
263276

264277
Union[int, Any] == Any
265278

266279
* You cannot subclass or instantiate a union.
267280

268-
* You cannot write `Union[X][Y]`
281+
* You cannot write ``Union[X][Y]``
269282

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]``.
271284

272285
.. class:: Optional
273286

274287
Optional type.
275288

276-
`Optional[X]` is equivalent to `Union[X, type(None)]`.
289+
``Optional[X]`` is equivalent to ``Union[X, type(None)]``.
277290

278291
.. class:: Tuple
279292

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
281294
with the first item of type X and the second of type Y.
282295

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
285298
of an int, a float and a string.
286299

287300
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, ...]``.
289302

290303
.. class:: Callable
291304

292-
Callable type; `Callable[[int], str]` is a function of (int) -> str.
305+
Callable type; ``Callable[[int], str]`` is a function of (int) -> str.
293306

294307
The subscription syntax must always be used with exactly two
295308
values: the argument list and the return type. The argument list
296309
must be a list of types; the return type must be a single type.
297310

298311
There is no syntax to indicate optional or keyword arguments,
299312
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]``.
303316

304317
.. class:: Generic
305318

@@ -326,57 +339,139 @@ The module defines the following classes, functions and decorators:
326339

327340
.. class:: Iterable(Generic[T_co])
328341

342+
A generic version of the :class:`collections.abc.Iterable`.
343+
329344
.. class:: Iterator(Iterable[T_co])
330345

346+
A generic version of the :class:`collections.abc.Iterator`.
347+
331348
.. class:: SupportsInt
332349

350+
An ABC with one abstract method `__int__`.
351+
333352
.. class:: SupportsFloat
334353

354+
An ABC with one abstract method `__float__`.
355+
335356
.. class:: SupportsAbs
336357

358+
An ABC with one abstract method `__abs__` that is covariant
359+
in its return type.
360+
337361
.. class:: SupportsRound
338362

363+
An ABC with one abstract method `__round__`
364+
that is covariant in its return type.
365+
339366
.. class:: Reversible
340367

368+
An ABC with one abstract method `__reversed__` returning
369+
an `Iterator[T_co]`.
370+
341371
.. class:: Container(Generic[T_co])
342372

373+
A generic version of :class:`collections.abc.Container`.
374+
343375
.. class:: AbstractSet(Sized, Iterable[T_co], Container[T_co])
344376

377+
A generic version of :class:`collections.abc.Set`.
378+
345379
.. class:: MutableSet(AbstractSet[T])
346380

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`.
348386

349387
.. class:: MutableMapping(Mapping[KT, VT])
350388

389+
A generic version of :class:`collections.abc.MutableMapping`.
390+
351391
.. class:: Sequence(Sized, Iterable[T_co], Container[T_co])
352392

393+
A generic version of :class:`collections.abc.Sequence`.
394+
353395
.. class:: MutableSequence(Sequence[T])
354396

397+
A generic version of :class:`collections.abc.MutableSequence`.
398+
355399
.. class:: ByteString(Sequence[int])
356400

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+
357409
.. class:: List(list, MutableSequence[T])
358410

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`.
360429

361430
.. class:: MappingView(Sized, Iterable[T_co])
362431

432+
A generic version of :class:`collections.abc.MappingView`.
433+
363434
.. class:: KeysView(MappingView[KT_co], AbstractSet[KT_co])
364435

436+
A generic version of :class:`collections.abc.KeysView`.
437+
365438
.. class:: ItemsView(MappingView, Generic[KT_co, VT_co])
366439

440+
A generic version of :class:`collections.abc.ItemsView`.
441+
367442
.. class:: ValuesView(MappingView[VT_co])
368443

444+
A generic version of :class:`collections.abc.ValuesView`.
445+
369446
.. class:: Dict(dict, MutableMapping[KT, VT])
370447

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+
371454
.. class:: Generator(Iterator[T_co], Generic[T_co, T_contra, V_co])
372455

373456
.. class:: io
374457

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`.
376464

377465
.. class:: re
378466

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]``.
380475

381476
.. function:: NamedTuple(typename, fields)
382477

0 commit comments

Comments
 (0)