Skip to content

Crossreferences to standard library in mypy docs, part 7 #7699

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Oct 13, 2019
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
120 changes: 60 additions & 60 deletions docs/source/protocols.rst
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ inherits class ``C``, it's also a subtype of ``C``, and instances of
``D`` can be used when ``C`` instances are expected. This form of
subtyping is used by default in mypy, since it's easy to understand
and produces clear and concise error messages, and since it matches
how the native ``isinstance()`` check works -- based on class
how the native :py:func:`isinstance <isinstance>` check works -- based on class
hierarchy. *Structural* subtyping can also be useful. Class ``D`` is
a structural subtype of class ``C`` if the former has all attributes
and methods of the latter, and with compatible types.
Expand All @@ -26,10 +26,10 @@ and structural subtyping in Python.
Predefined protocols
********************

The ``typing`` module defines various protocol classes that correspond
to common Python protocols, such as ``Iterable[T]``. If a class
defines a suitable ``__iter__`` method, mypy understands that it
implements the iterable protocol and is compatible with ``Iterable[T]``.
The :py:mod:`typing` module defines various protocol classes that correspond
to common Python protocols, such as :py:class:`Iterable[T] <typing.Iterable>`. If a class
defines a suitable :py:meth:`__iter__ <object.__iter__>` method, mypy understands that it
implements the iterable protocol and is compatible with :py:class:`Iterable[T] <typing.Iterable>`.
For example, ``IntList`` below is iterable, over ``int`` values:

.. code-block:: python
Expand All @@ -56,7 +56,7 @@ For example, ``IntList`` below is iterable, over ``int`` values:
print_numbered([4, 5]) # Also OK

The subsections below introduce all built-in protocols defined in
``typing`` and the signatures of the corresponding methods you need to define
:py:mod:`typing` and the signatures of the corresponding methods you need to define
to implement each protocol (the signatures can be left out, as always, but mypy
won't type check unannotated methods).

Expand All @@ -66,18 +66,18 @@ Iteration protocols
The iteration protocols are useful in many contexts. For example, they allow
iteration of objects in for loops.

``Iterable[T]``
---------------
:py:class:`Iterable[T] <typing.Iterable>`
-----------------------------------------
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please advise whether the refs in the section titles are useful.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I prefer not to have them (consistent with the earlier policy against code in titles. But then we need to edit the body text to include a ref, since it's still useful to have it.

Copy link
Contributor Author

@hoefling hoefling Oct 12, 2019

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe a generic line like "See also ProtocolName documentation." to each section? The stdlib docs don't shed more light on protocol types TBH; PEP 544 is the information source if one needs details (and it's not even mentioned in the typing documentation!).

Or maybe a line like "The ProtocolName type is defined in typing module.", just to point out where the type can be imported from?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let's put a line like

See also :py:class:`Iterable`.

at the end of each section.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

(and it's not even mentioned in the typing documentation!)

It is in the relevant version (i.e. Python 3.8): https://docs.python.org/3.8/library/typing.html

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I have removed the remote branch by accident, didn't mean to close this PR.


The :ref:`example above <predefined_protocols>` has a simple implementation of an
``__iter__`` method.
:py:meth:`__iter__ <object.__iter__>` method.

.. code-block:: python

def __iter__(self) -> Iterator[T]

``Iterator[T]``
---------------
:py:class:`Iterator[T] <typing.Iterator>`
-----------------------------------------

.. code-block:: python

Expand All @@ -88,29 +88,29 @@ Collection protocols
....................

Many of these are implemented by built-in container types such as
``list`` and ``dict``, and these are also useful for user-defined
:py:class:`list` and :py:class:`dict`, and these are also useful for user-defined
collection objects.

``Sized``
---------
:py:class:`~typing.Sized`
-------------------------

This is a type for objects that support ``len(x)``.
This is a type for objects that support :py:func:`len(x) <len>`.

.. code-block:: python

def __len__(self) -> int

``Container[T]``
----------------
:py:class:`Container[T] <typing.Container>`
-------------------------------------------

This is a type for objects that support the ``in`` operator.

.. code-block:: python

def __contains__(self, x: object) -> bool

``Collection[T]``
-----------------
:py:class:`Collection[T] <typing.Collection>`
---------------------------------------------

.. code-block:: python

Expand All @@ -124,70 +124,70 @@ One-off protocols
These protocols are typically only useful with a single standard
library function or class.

``Reversible[T]``
-----------------
:py:class:`Reversible[T] <typing.Reversible>`
---------------------------------------------

This is a type for objects that support ``reversed(x)``.
This is a type for objects that support :py:func:`reversed(x) <reversed>`.

.. code-block:: python

def __reversed__(self) -> Iterator[T]

``SupportsAbs[T]``
------------------
:py:class:`SupportsAbs[T] <typing.SupportsAbs>`
-----------------------------------------------

This is a type for objects that support ``abs(x)``. ``T`` is the type of
value returned by ``abs(x)``.
This is a type for objects that support :py:func:`abs(x) <abs>`. ``T`` is the type of
value returned by :py:func:`abs(x) <abs>`.

.. code-block:: python

def __abs__(self) -> T

``SupportsBytes``
-----------------
:py:class:`~typing.SupportsBytes`
---------------------------------

This is a type for objects that support ``bytes(x)``.
This is a type for objects that support :py:class:`bytes(x) <bytes>`.

.. code-block:: python

def __bytes__(self) -> bytes

.. _supports-int-etc:

``SupportsComplex``
-------------------
:py:class:`~typing.SupportsComplex`
-----------------------------------

This is a type for objects that support ``complex(x)``. Note that no arithmetic operations
This is a type for objects that support :py:class:`complex(x) <complex>`. Note that no arithmetic operations
are supported.

.. code-block:: python

def __complex__(self) -> complex

``SupportsFloat``
-----------------
:py:class:`~typing.SupportsFloat`
---------------------------------

This is a type for objects that support ``float(x)``. Note that no arithmetic operations
This is a type for objects that support :py:class:`float(x) <float>`. Note that no arithmetic operations
are supported.

.. code-block:: python

def __float__(self) -> float

``SupportsInt``
---------------
:py:class:`~typing.SupportsInt`
-------------------------------

This is a type for objects that support ``int(x)``. Note that no arithmetic operations
This is a type for objects that support :py:class:`int(x) <int>`. Note that no arithmetic operations
are supported.

.. code-block:: python

def __int__(self) -> int

``SupportsRound[T]``
--------------------
:py:class:`SupportsRound[T] <typing.SupportsRound>`
---------------------------------------------------

This is a type for objects that support ``round(x)``.
This is a type for objects that support :py:func:`round(x) <round>`.

.. code-block:: python

Expand All @@ -199,22 +199,22 @@ Async protocols
These protocols can be useful in async code. See :ref:`async-and-await`
for more information.

``Awaitable[T]``
----------------
:py:class:`Awaitable[T] <typing.Awaitable>`
-------------------------------------------

.. code-block:: python

def __await__(self) -> Generator[Any, None, T]

``AsyncIterable[T]``
--------------------
:py:class:`AsyncIterable[T] <typing.AsyncIterable>`
---------------------------------------------------

.. code-block:: python

def __aiter__(self) -> AsyncIterator[T]

``AsyncIterator[T]``
--------------------
:py:class:`AsyncIterator[T] <typing.AsyncIterator>`
---------------------------------------------------

.. code-block:: python

Expand All @@ -228,8 +228,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]``
---------------------
:py:class:`ContextManager[T] <typing.ContextManager>`
-----------------------------------------------------

.. code-block:: python

Expand All @@ -239,8 +239,8 @@ be used in ``with`` and ``async with`` statements.
exc_value: Optional[BaseException],
traceback: Optional[TracebackType]) -> Optional[bool]

``AsyncContextManager[T]``
--------------------------
:py:class:`AsyncContextManager[T] <typing.AsyncContextManager>`
---------------------------------------------------------------

.. code-block:: python

Expand Down Expand Up @@ -278,7 +278,7 @@ class:
close_all([Resource(), open('some/file')]) # Okay!

``Resource`` is a subtype of the ``SupportsClose`` protocol since it defines
a compatible ``close`` method. Regular file objects returned by ``open()`` are
a compatible ``close`` method. Regular file objects returned by :py:func:`open` are
similarly compatible with the protocol, as they support ``close()``.

.. note::
Expand Down Expand Up @@ -379,7 +379,7 @@ such as trees and linked lists:
Using isinstance() with protocols
*********************************

You can use a protocol class with ``isinstance()`` if you decorate it
You can use a protocol class with :py:func:`isinstance` if you decorate it
with the ``@runtime_checkable`` class decorator. The decorator adds
support for basic runtime structural checks:

Expand All @@ -399,11 +399,11 @@ support for basic runtime structural checks:
if isinstance(mug, Portable):
use(mug.handles) # Works statically and at runtime

``isinstance()`` also works with the :ref:`predefined protocols <predefined_protocols>`
in ``typing`` such as ``Iterable``.
:py:func:`isinstance` also works with the :ref:`predefined protocols <predefined_protocols>`
in :py:mod:`typing` such as :py:class:`~typing.Iterable`.

.. note::
``isinstance()`` with protocols is not completely safe at runtime.
:py:func:`isinstance` with protocols is not completely safe at runtime.
For example, signatures of methods are not checked. The runtime
implementation only checks that all protocol members are defined.

Expand All @@ -413,8 +413,8 @@ Callback protocols
******************

Protocols can be used to define flexible callback types that are hard
(or even impossible) to express using the ``Callable[...]`` syntax, such as variadic,
overloaded, and complex generic callbacks. They are defined with a special ``__call__``
(or even impossible) to express using the :py:data:`Callable[...] <typing.Callable>` syntax, such as variadic,
overloaded, and complex generic callbacks. They are defined with a special :py:meth:`__call__ <object.__call__>`
member:

.. code-block:: python
Expand All @@ -438,8 +438,8 @@ member:
batch_proc([], bad_cb) # Error! Argument 2 has incompatible type because of
# different name and kind in the callback

Callback protocols and ``Callable[...]`` types can be used interchangeably.
Keyword argument names in ``__call__`` methods must be identical, unless
Callback protocols and :py:class:`~typing.Callable` types can be used interchangeably.
Keyword argument names in :py:meth:`__call__ <object.__call__>` methods must be identical, unless
a double underscore prefix is used. For example:

.. code-block:: python
Expand Down
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy