[go: up one dir, main page]

Skip to content

Commit

Permalink
Update various references to deprecated type aliases in docs (#17829)
Browse files Browse the repository at this point in the history
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 <jelle.zijlstra@gmail.com>
  • Loading branch information
JukkaL and JelleZijlstra authored Sep 26, 2024
1 parent 6336ce1 commit 0dfb718
Show file tree
Hide file tree
Showing 17 changed files with 161 additions and 124 deletions.
12 changes: 6 additions & 6 deletions docs/source/additional_features.rst
Original file line number Diff line number Diff line change
Expand Up @@ -363,20 +363,20 @@ Extended Callable types
This feature is deprecated. You can use
:ref:`callback protocols <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)
Expand Down Expand Up @@ -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
Expand All @@ -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
Expand Down
12 changes: 8 additions & 4 deletions docs/source/cheat_sheet_py3.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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:
...
Expand All @@ -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])
Expand Down
3 changes: 2 additions & 1 deletion docs/source/class_basics.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand Down
4 changes: 1 addition & 3 deletions docs/source/command_line.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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!
...
Expand Down
7 changes: 4 additions & 3 deletions docs/source/common_issues.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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]:
Expand All @@ -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):
Expand Down
4 changes: 1 addition & 3 deletions docs/source/dynamic_typing.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
6 changes: 2 additions & 4 deletions docs/source/error_code_list.rst
Original file line number Diff line number Diff line change
Expand Up @@ -124,8 +124,6 @@ Example:

.. code-block:: python
from typing import Sequence
def greet(name: str) -> None:
print('hello', name)
Expand Down Expand Up @@ -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:
Expand Down
4 changes: 2 additions & 2 deletions docs/source/error_code_list2.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -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]
Expand Down
9 changes: 5 additions & 4 deletions docs/source/faq.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
40 changes: 25 additions & 15 deletions docs/source/generics.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -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:
Expand All @@ -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])
Expand Down Expand Up @@ -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:
Expand All @@ -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')
Expand All @@ -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]:
Expand All @@ -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')
Expand All @@ -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:
Expand All @@ -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')
Expand All @@ -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]:
...
Expand All @@ -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])
Expand All @@ -1027,7 +1035,8 @@ achieved by combining with :py:func:`@overload <typing.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
Expand Down Expand Up @@ -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])
Expand All @@ -1077,7 +1087,7 @@ Generic protocols

Mypy supports generic protocols (see also :ref:`protocol-types`). Several
:ref:`predefined protocols <predefined_protocols>` are generic, such as
:py:class:`Iterable[T] <typing.Iterable>`, and you can define additional
:py:class:`Iterable[T] <collections.abc.Iterable>`, and you can define additional
generic protocols. Generic protocols mostly follow the normal rules for
generic classes. Example (Python 3.12 syntax):

Expand Down Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion docs/source/getting_started.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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::

Expand Down
Loading

0 comments on commit 0dfb718

Please sign in to comment.