From 0dfb7184d72d1aad951b1eed1541e3162d7ca040 Mon Sep 17 00:00:00 2001 From: Jukka Lehtosalo Date: Thu, 26 Sep 2024 11:19:15 +0100 Subject: [PATCH] Update various references to deprecated type aliases in docs (#17829) Use `collections.abc.Iterable`, for example, instead of `typing.Iterable`, unless we are discussing support for older Python versions. The latter has been deprecated since Python 3.9. Also update a few other out-of-date things that I happened to notice. Part of the motivation is that Python 3.8 will reach end of life in October, so we can soon start mostly assuming that users are on 3.9 or newer (even if we'll continue supporting 3.8 for a while still). --------- Co-authored-by: Jelle Zijlstra --- docs/source/additional_features.rst | 12 +-- docs/source/cheat_sheet_py3.rst | 12 ++- docs/source/class_basics.rst | 3 +- docs/source/command_line.rst | 4 +- docs/source/common_issues.rst | 7 +- docs/source/dynamic_typing.rst | 4 +- docs/source/error_code_list.rst | 6 +- docs/source/error_code_list2.rst | 4 +- docs/source/faq.rst | 9 +- docs/source/generics.rst | 40 +++++---- docs/source/getting_started.rst | 2 +- docs/source/kinds_of_types.rst | 13 ++- docs/source/more_types.rst | 22 +++-- docs/source/protocols.rst | 133 ++++++++++++++++------------ docs/source/runtime_troubles.rst | 5 +- docs/source/type_narrowing.rst | 5 +- docs/source/typed_dict.rst | 4 +- 17 files changed, 161 insertions(+), 124 deletions(-) diff --git a/docs/source/additional_features.rst b/docs/source/additional_features.rst index a9c3177d32a2f..e7c162a0b0df9 100644 --- a/docs/source/additional_features.rst +++ b/docs/source/additional_features.rst @@ -363,20 +363,20 @@ Extended Callable types This feature is deprecated. You can use :ref:`callback protocols ` as a replacement. -As an experimental mypy extension, you can specify :py:data:`~typing.Callable` types +As an experimental mypy extension, you can specify :py:class:`~collections.abc.Callable` types that support keyword arguments, optional arguments, and more. When -you specify the arguments of a :py:data:`~typing.Callable`, you can choose to supply just +you specify the arguments of a :py:class:`~collections.abc.Callable`, you can choose to supply just the type of a nameless positional argument, or an "argument specifier" representing a more complicated form of argument. This allows one to more closely emulate the full range of possibilities given by the ``def`` statement in Python. As an example, here's a complicated function definition and the -corresponding :py:data:`~typing.Callable`: +corresponding :py:class:`~collections.abc.Callable`: .. code-block:: python - from typing import Callable + from collections.abc import Callable from mypy_extensions import (Arg, DefaultArg, NamedArg, DefaultNamedArg, VarArg, KwArg) @@ -449,7 +449,7 @@ purpose: In all cases, the ``type`` argument defaults to ``Any``, and if the ``name`` argument is omitted the argument has no name (the name is required for ``NamedArg`` and ``DefaultNamedArg``). A basic -:py:data:`~typing.Callable` such as +:py:class:`~collections.abc.Callable` such as .. code-block:: python @@ -461,7 +461,7 @@ is equivalent to the following: MyFunc = Callable[[Arg(int), Arg(str), Arg(int)], float] -A :py:data:`~typing.Callable` with unspecified argument types, such as +A :py:class:`~collections.abc.Callable` with unspecified argument types, such as .. code-block:: python diff --git a/docs/source/cheat_sheet_py3.rst b/docs/source/cheat_sheet_py3.rst index ca6dfc8eb63a6..eb2f8228cf529 100644 --- a/docs/source/cheat_sheet_py3.rst +++ b/docs/source/cheat_sheet_py3.rst @@ -88,7 +88,8 @@ Functions .. code-block:: python - from typing import Callable, Iterator, Union, Optional + from collections.abc import Iterator, Callable + from typing import Union, Optional # This is how you annotate a function definition def stringify(num: int) -> str: @@ -274,7 +275,8 @@ that are common in idiomatic Python are standardized. .. code-block:: python - from typing import Mapping, MutableMapping, Sequence, Iterable + from collections.abc import Mapping, MutableMapping, Sequence, Iterable + # or 'from typing import ...' (required in Python 3.8) # Use Iterable for generic iterables (anything usable in "for"), # and Sequence where a sequence (supporting "len" and "__getitem__") is @@ -354,7 +356,8 @@ syntax: .. code-block:: python - from typing import Any, Callable + from collections.abc import Callable + from typing import Any def bare_decorator[F: Callable[..., Any]](func: F) -> F: ... @@ -366,7 +369,8 @@ The same example using pre-3.12 syntax: .. code-block:: python - from typing import Any, Callable, TypeVar + from collections.abc import Callable + from typing import Any, TypeVar F = TypeVar('F', bound=Callable[..., Any]) diff --git a/docs/source/class_basics.rst b/docs/source/class_basics.rst index 1d80da5830ec9..241dbeae0f447 100644 --- a/docs/source/class_basics.rst +++ b/docs/source/class_basics.rst @@ -152,7 +152,8 @@ between class and instance variables with callable types. For example: .. code-block:: python - from typing import Callable, ClassVar + from collections.abc import Callable + from typing import ClassVar class A: foo: Callable[[int], None] diff --git a/docs/source/command_line.rst b/docs/source/command_line.rst index a89a3c85d4eea..3d4b841e0a7c8 100644 --- a/docs/source/command_line.rst +++ b/docs/source/command_line.rst @@ -630,13 +630,11 @@ of the above sections. .. code-block:: python - from typing import Text - items: list[int] if 'some string' in items: # Error: non-overlapping container check! ... - text: Text + text: str if text != b'other bytes': # Error: non-overlapping equality check! ... diff --git a/docs/source/common_issues.rst b/docs/source/common_issues.rst index cfe82e19e77b8..c34d20775cfdd 100644 --- a/docs/source/common_issues.rst +++ b/docs/source/common_issues.rst @@ -363,7 +363,8 @@ explicit type cast: .. code-block:: python - from typing import Sequence, cast + from collections.abc import Sequence + from typing import cast def find_first_str(a: Sequence[object]) -> str: index = next((i for i, s in enumerate(a) if isinstance(s, str)), -1) @@ -700,7 +701,7 @@ This example demonstrates both safe and unsafe overrides: .. code-block:: python - from typing import Sequence, List, Iterable + from collections.abc import Sequence, Iterable class A: def test(self, t: Sequence[int]) -> Sequence[str]: @@ -713,7 +714,7 @@ This example demonstrates both safe and unsafe overrides: class NarrowerArgument(A): # A more specific argument type isn't accepted - def test(self, t: List[int]) -> Sequence[str]: # Error + def test(self, t: list[int]) -> Sequence[str]: # Error ... class NarrowerReturn(A): diff --git a/docs/source/dynamic_typing.rst b/docs/source/dynamic_typing.rst index d3476de2ca641..1c31a535bdc1d 100644 --- a/docs/source/dynamic_typing.rst +++ b/docs/source/dynamic_typing.rst @@ -81,9 +81,7 @@ treated as ``Any``: .. code-block:: python - from typing import List - - def f(x: List) -> None: + def f(x: list) -> None: reveal_type(x) # Revealed type is "builtins.list[Any]" reveal_type(x[0]) # Revealed type is "Any" x[0].anything_goes() # OK diff --git a/docs/source/error_code_list.rst b/docs/source/error_code_list.rst index ec069fdcba1dd..bb745d9d5c986 100644 --- a/docs/source/error_code_list.rst +++ b/docs/source/error_code_list.rst @@ -124,8 +124,6 @@ Example: .. code-block:: python - from typing import Sequence - def greet(name: str) -> None: print('hello', name) @@ -210,11 +208,11 @@ This example incorrectly uses the function ``log`` as a type: for x in objs: f(x) -You can use :py:data:`~typing.Callable` as the type for callable objects: +You can use :py:class:`~collections.abc.Callable` as the type for callable objects: .. code-block:: python - from typing import Callable + from collections.abc import Callable # OK def log_all(objs: list[object], f: Callable[[object], None]) -> None: diff --git a/docs/source/error_code_list2.rst b/docs/source/error_code_list2.rst index 0655ef2d35d87..6d50e217a77de 100644 --- a/docs/source/error_code_list2.rst +++ b/docs/source/error_code_list2.rst @@ -270,7 +270,7 @@ example: # mypy: enable-error-code="possibly-undefined" - from typing import Iterable + from collections.abc import Iterable def test(values: Iterable[int], flag: bool) -> None: if flag: @@ -318,7 +318,7 @@ Example: .. code-block:: python - from typing import Iterable + from collections.abc import Iterable def transform(items: Iterable[int]) -> list[int]: # Error: "items" has type "Iterable[int]" which can always be true in boolean context. Consider using "Collection[int]" instead. [truthy-iterable] diff --git a/docs/source/faq.rst b/docs/source/faq.rst index 195805382cd3b..b7f5e3759a7e8 100644 --- a/docs/source/faq.rst +++ b/docs/source/faq.rst @@ -102,8 +102,8 @@ Structural subtyping can be thought of as "static duck typing". Some argue that structural subtyping is better suited for languages with duck typing such as Python. Mypy however primarily uses nominal subtyping, leaving structural subtyping mostly opt-in (except for built-in protocols -such as :py:class:`~typing.Iterable` that always support structural subtyping). Here are some -reasons why: +such as :py:class:`~collections.abc.Iterable` that always support structural +subtyping). Here are some reasons why: 1. It is easy to generate short and informative error messages when using a nominal type system. This is especially important when @@ -140,13 +140,14 @@ How are mypy programs different from normal Python? Since you use a vanilla Python implementation to run mypy programs, mypy programs are also Python programs. The type checker may give warnings for some valid Python code, but the code is still always -runnable. Also, some Python features and syntax are still not +runnable. Also, a few Python features are still not supported by mypy, but this is gradually improving. The obvious difference is the availability of static type checking. The section :ref:`common_issues` mentions some modifications to Python code that may be required to make code type -check without errors. Also, your code must make attributes explicit. +check without errors. Also, your code must make defined +attributes explicit. Mypy supports modular, efficient type checking, and this seems to rule out type checking some language features, such as arbitrary diff --git a/docs/source/generics.rst b/docs/source/generics.rst index 3d175cedbb932..982adf9324afd 100644 --- a/docs/source/generics.rst +++ b/docs/source/generics.rst @@ -591,7 +591,7 @@ Let us illustrate this by few simple examples: Covariance should feel relatively intuitive, but contravariance and invariance can be harder to reason about. -* :py:data:`~typing.Callable` is an example of type that behaves contravariant +* :py:class:`~collections.abc.Callable` is an example of type that behaves contravariant in types of arguments. That is, ``Callable[[Shape], int]`` is a subtype of ``Callable[[Triangle], int]``, despite ``Shape`` being a supertype of ``Triangle``. To understand this, consider: @@ -833,7 +833,8 @@ Here's how one could annotate the decorator (Python 3.12 syntax): .. code-block:: python - from typing import Any, Callable, cast + from collections.abc import Callable + from typing import Any, cast # A decorator that preserves the signature. def printing_decorator[F: Callable[..., Any]](func: F) -> F: @@ -854,7 +855,8 @@ Here is the example using the legacy syntax (Python 3.11 and earlier): .. code-block:: python - from typing import Any, Callable, TypeVar, cast + from collections.abc import Callable + from typing import Any, TypeVar, cast F = TypeVar('F', bound=Callable[..., Any]) @@ -887,7 +889,7 @@ for a more faithful type annotation (Python 3.12 syntax): .. code-block:: python - from typing import Callable + from collections.abc import Callable def printing_decorator[**P, T](func: Callable[P, T]) -> Callable[P, T]: def wrapper(*args: P.args, **kwds: P.kwargs) -> T: @@ -900,7 +902,8 @@ The same is possible using the legacy syntax with :py:class:`~typing.ParamSpec` .. code-block:: python - from typing import Callable, TypeVar + from collections.abc import Callable + from typing import TypeVar from typing_extensions import ParamSpec P = ParamSpec('P') @@ -917,7 +920,7 @@ alter the signature of the input function (Python 3.12 syntax): .. code-block:: python - from typing import Callable + from collections.abc import Callable # We reuse 'P' in the return type, but replace 'T' with 'str' def stringify[**P, T](func: Callable[P, T]) -> Callable[P, str]: @@ -937,7 +940,8 @@ Here is the above example using the legacy syntax (Python 3.11 and earlier): .. code-block:: python - from typing import Callable, TypeVar + from collections.abc import Callable + from typing import TypeVar from typing_extensions import ParamSpec P = ParamSpec('P') @@ -953,7 +957,8 @@ You can also insert an argument in a decorator (Python 3.12 syntax): .. code-block:: python - from typing import Callable, Concatenate + from collections.abc import Callable + from typing import Concatenate def printing_decorator[**P, T](func: Callable[P, T]) -> Callable[Concatenate[str, P], T]: def wrapper(msg: str, /, *args: P.args, **kwds: P.kwargs) -> T: @@ -971,7 +976,8 @@ Here is the same function using the legacy syntax (Python 3.11 and earlier): .. code-block:: python - from typing import Callable, TypeVar + from collections.abc import Callable + from typing import TypeVar from typing_extensions import Concatenate, ParamSpec P = ParamSpec('P') @@ -993,7 +999,8 @@ similarly supported via generics (Python 3.12 syntax): .. code-block:: python - from typing import Any, Callable + from colletions.abc import Callable + from typing import Any def route[F: Callable[..., Any]](url: str) -> Callable[[F], F]: ... @@ -1011,7 +1018,8 @@ Here is the example using the legacy syntax (Python 3.11 and earlier): .. code-block:: python - from typing import Any, Callable, TypeVar + from collections.abc import Callable + from typing import Any, TypeVar F = TypeVar('F', bound=Callable[..., Any]) @@ -1027,7 +1035,8 @@ achieved by combining with :py:func:`@overload ` (Python 3.12 s .. code-block:: python - from typing import Any, Callable, overload + from collections.abc import Callable + from typing import Any, overload # Bare decorator usage @overload @@ -1057,7 +1066,8 @@ Here is the decorator from the example using the legacy syntax .. code-block:: python - from typing import Any, Callable, Optional, TypeVar, overload + from collections.abc import Callable + from typing import Any, Optional, TypeVar, overload F = TypeVar('F', bound=Callable[..., Any]) @@ -1077,7 +1087,7 @@ Generic protocols Mypy supports generic protocols (see also :ref:`protocol-types`). Several :ref:`predefined protocols ` are generic, such as -:py:class:`Iterable[T] `, and you can define additional +:py:class:`Iterable[T] `, and you can define additional generic protocols. Generic protocols mostly follow the normal rules for generic classes. Example (Python 3.12 syntax): @@ -1200,7 +1210,7 @@ type aliases (it also supports non-generic type aliases): .. code-block:: python - from typing import Iterable, Callable + from collections.abc import Callable, Iterable type TInt[S] = tuple[int, S] type UInt[S] = S | int diff --git a/docs/source/getting_started.rst b/docs/source/getting_started.rst index 049d7af003b5d..12422ef85bde4 100644 --- a/docs/source/getting_started.rst +++ b/docs/source/getting_started.rst @@ -215,7 +215,7 @@ generic types or your own type aliases), look through the For brevity, we often omit imports from :py:mod:`typing` or :py:mod:`collections.abc` in code examples, but mypy will give an error if you use types such as - :py:class:`~typing.Iterable` without first importing them. + :py:class:`~collections.abc.Iterable` without first importing them. .. note:: diff --git a/docs/source/kinds_of_types.rst b/docs/source/kinds_of_types.rst index e645a27095d1d..afdf07a559da5 100644 --- a/docs/source/kinds_of_types.rst +++ b/docs/source/kinds_of_types.rst @@ -136,7 +136,7 @@ purpose. Example: .. note:: Usually it's a better idea to use ``Sequence[T]`` instead of ``tuple[T, ...]``, as - :py:class:`~typing.Sequence` is also compatible with lists and other non-tuple sequences. + :py:class:`~collections.abc.Sequence` is also compatible with lists and other non-tuple sequences. .. note:: @@ -155,7 +155,7 @@ and returns ``Rt`` is ``Callable[[A1, ..., An], Rt]``. Example: .. code-block:: python - from typing import Callable + from collections.abc import Callable def twice(i: int, next: Callable[[int], int]) -> int: return next(next(i)) @@ -165,6 +165,11 @@ and returns ``Rt`` is ``Callable[[A1, ..., An], Rt]``. Example: print(twice(3, add)) # 5 +.. note:: + + Import :py:data:`Callable[...] ` from ``typing`` instead + of ``collections.abc`` if you use Python 3.8 or earlier. + You can only have positional arguments, and only ones without default values, in callable types. These cover the vast majority of uses of callable types, but sometimes this isn't quite enough. Mypy recognizes @@ -178,7 +183,7 @@ Any)`` function signature. Example: .. code-block:: python - from typing import Callable + from collections.abc import Callable def arbitrary_call(f: Callable[..., int]) -> int: return f('x') + f(y=2) # OK @@ -205,7 +210,7 @@ Callables can also be used against type objects, matching their .. code-block:: python - from typing import Callable + from collections.abc import Callable class C: def __init__(self, app: str) -> None: diff --git a/docs/source/more_types.rst b/docs/source/more_types.rst index 2d3ce5925c02d..26edd9ef252c0 100644 --- a/docs/source/more_types.rst +++ b/docs/source/more_types.rst @@ -253,7 +253,7 @@ calls like ``mouse_event(5, 25, 2)``. As another example, suppose we want to write a custom container class that implements the :py:meth:`__getitem__ ` method (``[]`` bracket indexing). If this method receives an integer we return a single item. If it receives a -``slice``, we return a :py:class:`~typing.Sequence` of items. +``slice``, we return a :py:class:`~collections.abc.Sequence` of items. We can precisely encode this relationship between the argument and the return type by using overloads like so (Python 3.12 syntax): @@ -760,7 +760,8 @@ some tricky methods (Python 3.12 syntax): .. code-block:: python - from typing import overload, Callable + from collections.abc import Callable + from typing import overload class Tag[T]: @overload @@ -875,8 +876,8 @@ expect to get back when ``await``-ing the coroutine. The result of calling an ``async def`` function *without awaiting* will automatically be inferred to be a value of type -:py:class:`Coroutine[Any, Any, T] `, which is a subtype of -:py:class:`Awaitable[T] `: +:py:class:`Coroutine[Any, Any, T] `, which is a subtype of +:py:class:`Awaitable[T] `: .. code-block:: python @@ -889,11 +890,12 @@ Asynchronous iterators ---------------------- If you have an asynchronous iterator, you can use the -:py:class:`~typing.AsyncIterator` type in your annotations: +:py:class:`~collections.abc.AsyncIterator` type in your annotations: .. code-block:: python - from typing import Optional, AsyncIterator + from collections.abc import AsyncIterator + from typing import Optional import asyncio class arange: @@ -926,7 +928,8 @@ async iterators: .. code-block:: python - from typing import AsyncGenerator, Optional + from collections.abc import AsyncGenerator + from typing import Optional import asyncio # Could also type this as returning AsyncIterator[int] @@ -943,7 +946,7 @@ One common confusion is that the presence of a ``yield`` statement in an .. code-block:: python - from typing import AsyncIterator + from collections.abc import AsyncIterator async def arange(stop: int) -> AsyncIterator[int]: # When called, arange gives you an async iterator @@ -969,7 +972,8 @@ This can sometimes come up when trying to define base classes, Protocols or over .. code-block:: python - from typing import AsyncIterator, Protocol, overload + from collections.abc import AsyncIterator + from typing import Protocol, overload class LauncherIncorrect(Protocol): # Because launch does not have yield, this has type diff --git a/docs/source/protocols.rst b/docs/source/protocols.rst index e143808e6c251..8cb53b1fd5cec 100644 --- a/docs/source/protocols.rst +++ b/docs/source/protocols.rst @@ -27,15 +27,17 @@ of protocols and structural subtyping in Python. Predefined protocols ******************** -The :py:mod:`typing` module defines various protocol classes that correspond -to common Python protocols, such as :py:class:`Iterable[T] `. If a class +The :py:mod:`collections.abc`, :py:mod:`typing` and other stdlib modules define +various protocol classes that correspond to common Python protocols, such as +:py:class:`Iterable[T] `. If a class defines a suitable :py:meth:`__iter__ ` method, mypy understands that it -implements the iterable protocol and is compatible with :py:class:`Iterable[T] `. +implements the iterable protocol and is compatible with :py:class:`Iterable[T] `. For example, ``IntList`` below is iterable, over ``int`` values: .. code-block:: python - from typing import Iterator, Iterable, Optional + from collections.abc import Iterator, Iterable + from typing import Optional class IntList: def __init__(self, value: int, next: Optional['IntList']) -> None: @@ -56,9 +58,18 @@ For example, ``IntList`` below is iterable, over ``int`` values: print_numbered(x) # OK print_numbered([4, 5]) # Also OK -:ref:`predefined_protocols_reference` lists all protocols defined in -:py:mod:`typing` and the signatures of the corresponding methods you need to define -to implement each protocol. +:ref:`predefined_protocols_reference` lists various protocols defined in +:py:mod:`collections.abc` and :py:mod:`typing` and the signatures of the corresponding methods +you need to define to implement each protocol. + +.. note:: + ``typing`` also contains deprecated aliases to protocols and ABCs defined in + :py:mod:`collections.abc`, such as :py:class:`Iterable[T] `. + These are only necessary in Python 3.8 and earlier, since the protocols in + ``collections.abc`` didn't yet support subscripting (``[]``) in Python 3.8, + but the aliases in ``typing`` have always supported + subscripting. In Python 3.9 and later, the aliases in ``typing`` don't provide + any extra functionality. Simple user-defined protocols ***************************** @@ -68,7 +79,8 @@ class: .. code-block:: python - from typing import Iterable, Protocol + from collections.abc import Iterable + from typing import Protocol class SupportsClose(Protocol): # Empty method body (explicit '...') @@ -290,13 +302,15 @@ Callback protocols ****************** Protocols can be used to define flexible callback types that are hard -(or even impossible) to express using the :py:data:`Callable[...] ` syntax, such as variadic, -overloaded, and complex generic callbacks. They are defined with a special :py:meth:`__call__ ` -member: +(or even impossible) to express using the +:py:class:`Callable[...] ` syntax, +such as variadic, overloaded, and complex generic callbacks. They are defined with a +special :py:meth:`__call__ ` member: .. code-block:: python - from typing import Optional, Iterable, Protocol + from collections.abc import Iterable + from typing import Optional, Protocol class Combiner(Protocol): def __call__(self, *vals: bytes, maxlen: Optional[int] = None) -> list[bytes]: ... @@ -314,13 +328,14 @@ member: batch_proc([], bad_cb) # Error! Argument 2 has incompatible type because of # different name and kind in the callback -Callback protocols and :py:data:`~typing.Callable` types can be used mostly interchangeably. +Callback protocols and :py:class:`~collections.abc.Callable` types can be used mostly interchangeably. Parameter names in :py:meth:`__call__ ` methods must be identical, unless the parameters are positional-only. Example (using the legacy syntax for generic functions): .. code-block:: python - from typing import Callable, Protocol, TypeVar + from collections.abc import Callable + from typing import Protocol, TypeVar T = TypeVar('T') @@ -345,8 +360,8 @@ Iteration protocols The iteration protocols are useful in many contexts. For example, they allow iteration of objects in for loops. -Iterable[T] ------------ +collections.abc.Iterable[T] +--------------------------- The :ref:`example above ` has a simple implementation of an :py:meth:`__iter__ ` method. @@ -355,17 +370,17 @@ The :ref:`example above ` has a simple implementation of a def __iter__(self) -> Iterator[T] -See also :py:class:`~typing.Iterable`. +See also :py:class:`~collections.abc.Iterable`. -Iterator[T] ------------ +collections.abc.Iterator[T] +--------------------------- .. code-block:: python def __next__(self) -> T def __iter__(self) -> Iterator[T] -See also :py:class:`~typing.Iterator`. +See also :py:class:`~collections.abc.Iterator`. Collection protocols .................... @@ -374,8 +389,8 @@ Many of these are implemented by built-in container types such as :py:class:`list` and :py:class:`dict`, and these are also useful for user-defined collection objects. -Sized ------ +collections.abc.Sized +--------------------- This is a type for objects that support :py:func:`len(x) `. @@ -383,10 +398,10 @@ This is a type for objects that support :py:func:`len(x) `. def __len__(self) -> int -See also :py:class:`~typing.Sized`. +See also :py:class:`~collections.abc.Sized`. -Container[T] ------------- +collections.abc.Container[T] +---------------------------- This is a type for objects that support the ``in`` operator. @@ -394,10 +409,10 @@ This is a type for objects that support the ``in`` operator. def __contains__(self, x: object) -> bool -See also :py:class:`~typing.Container`. +See also :py:class:`~collections.abc.Container`. -Collection[T] -------------- +collections.abc.Collection[T] +----------------------------- .. code-block:: python @@ -405,7 +420,7 @@ Collection[T] def __iter__(self) -> Iterator[T] def __contains__(self, x: object) -> bool -See also :py:class:`~typing.Collection`. +See also :py:class:`~collections.abc.Collection`. One-off protocols ................. @@ -413,8 +428,8 @@ One-off protocols These protocols are typically only useful with a single standard library function or class. -Reversible[T] -------------- +collections.abc.Reversible[T] +----------------------------- This is a type for objects that support :py:func:`reversed(x) `. @@ -422,10 +437,10 @@ This is a type for objects that support :py:func:`reversed(x) `. def __reversed__(self) -> Iterator[T] -See also :py:class:`~typing.Reversible`. +See also :py:class:`~collections.abc.Reversible`. -SupportsAbs[T] --------------- +typing.SupportsAbs[T] +--------------------- This is a type for objects that support :py:func:`abs(x) `. ``T`` is the type of value returned by :py:func:`abs(x) `. @@ -436,8 +451,8 @@ value returned by :py:func:`abs(x) `. See also :py:class:`~typing.SupportsAbs`. -SupportsBytes -------------- +typing.SupportsBytes +-------------------- This is a type for objects that support :py:class:`bytes(x) `. @@ -449,8 +464,8 @@ See also :py:class:`~typing.SupportsBytes`. .. _supports-int-etc: -SupportsComplex ---------------- +typing.SupportsComplex +---------------------- This is a type for objects that support :py:class:`complex(x) `. Note that no arithmetic operations are supported. @@ -461,8 +476,8 @@ are supported. See also :py:class:`~typing.SupportsComplex`. -SupportsFloat -------------- +typing.SupportsFloat +-------------------- This is a type for objects that support :py:class:`float(x) `. Note that no arithmetic operations are supported. @@ -473,8 +488,8 @@ are supported. See also :py:class:`~typing.SupportsFloat`. -SupportsInt ------------ +typing.SupportsInt +------------------ This is a type for objects that support :py:class:`int(x) `. Note that no arithmetic operations are supported. @@ -485,8 +500,8 @@ are supported. See also :py:class:`~typing.SupportsInt`. -SupportsRound[T] ----------------- +typing.SupportsRound[T] +----------------------- This is a type for objects that support :py:func:`round(x) `. @@ -502,33 +517,33 @@ Async protocols These protocols can be useful in async code. See :ref:`async-and-await` for more information. -Awaitable[T] ------------- +collections.abc.Awaitable[T] +---------------------------- .. code-block:: python def __await__(self) -> Generator[Any, None, T] -See also :py:class:`~typing.Awaitable`. +See also :py:class:`~collections.abc.Awaitable`. -AsyncIterable[T] ----------------- +collections.abc.AsyncIterable[T] +-------------------------------- .. code-block:: python def __aiter__(self) -> AsyncIterator[T] -See also :py:class:`~typing.AsyncIterable`. +See also :py:class:`~collections.abc.AsyncIterable`. -AsyncIterator[T] ----------------- +collections.abc.AsyncIterator[T] +-------------------------------- .. code-block:: python def __anext__(self) -> Awaitable[T] def __aiter__(self) -> AsyncIterator[T] -See also :py:class:`~typing.AsyncIterator`. +See also :py:class:`~collections.abc.AsyncIterator`. Context manager protocols ......................... @@ -537,8 +552,8 @@ There are two protocols for context managers -- one for regular context managers and one for async ones. These allow defining objects that can be used in ``with`` and ``async with`` statements. -ContextManager[T] ------------------ +contextlib.AbstractContextManager[T] +------------------------------------ .. code-block:: python @@ -548,10 +563,10 @@ ContextManager[T] exc_value: Optional[BaseException], traceback: Optional[TracebackType]) -> Optional[bool] -See also :py:class:`~typing.ContextManager`. +See also :py:class:`~contextlib.AbstractContextManager`. -AsyncContextManager[T] ----------------------- +contextlib.AbstractAsyncContextManager[T] +----------------------------------------- .. code-block:: python @@ -561,4 +576,4 @@ AsyncContextManager[T] exc_value: Optional[BaseException], traceback: Optional[TracebackType]) -> Awaitable[Optional[bool]] -See also :py:class:`~typing.AsyncContextManager`. +See also :py:class:`~contextlib.AbstractAsyncContextManager`. diff --git a/docs/source/runtime_troubles.rst b/docs/source/runtime_troubles.rst index ee4cdf274ebe6..9e7df05e879e1 100644 --- a/docs/source/runtime_troubles.rst +++ b/docs/source/runtime_troubles.rst @@ -21,8 +21,9 @@ problems you may encounter. String literal types and type comments -------------------------------------- -Mypy allows you to add type annotations using ``# type:`` type comments. -For example: +Mypy lets you add type annotations using the (now deprecated) ``# type:`` +type comment syntax. These were required with Python versions older than 3.6, +since they didn't support type annotations on variables. Example: .. code-block:: python diff --git a/docs/source/type_narrowing.rst b/docs/source/type_narrowing.rst index 131171844dfe6..0f016497113e9 100644 --- a/docs/source/type_narrowing.rst +++ b/docs/source/type_narrowing.rst @@ -114,7 +114,7 @@ So, we know what ``callable()`` will return. For example: .. code-block:: python - from typing import Callable + from collections.abc import Callable x: Callable[[], int] @@ -128,7 +128,8 @@ for callable and non-callable parts: .. code-block:: python - from typing import Callable, Union + from collections.abc import Callable + from typing import Union x: Union[int, Callable[[], int]] diff --git a/docs/source/typed_dict.rst b/docs/source/typed_dict.rst index c379b5449eaea..e69b3895c668b 100644 --- a/docs/source/typed_dict.rst +++ b/docs/source/typed_dict.rst @@ -89,7 +89,7 @@ A ``TypedDict`` object is not a subtype of the regular ``dict[...]`` type (and vice versa), since :py:class:`dict` allows arbitrary keys to be added and removed, unlike ``TypedDict``. However, any ``TypedDict`` object is a subtype of (that is, compatible with) ``Mapping[str, object]``, since -:py:class:`~typing.Mapping` only provides read-only access to the dictionary items: +:py:class:`~collections.abc.Mapping` only provides read-only access to the dictionary items: .. code-block:: python @@ -158,7 +158,7 @@ You must use string literals as keys when calling most of the methods, as otherwise mypy won't be able to check that the key is valid. List of supported operations: -* Anything included in :py:class:`~typing.Mapping`: +* Anything included in :py:class:`~collections.abc.Mapping`: * ``d[key]`` * ``key in d``