Skip to content

Crossreferences to standard library in mypy docs, part 3 #7677

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 10, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
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
4 changes: 2 additions & 2 deletions docs/source/class_basics.rst
Original file line number Diff line number Diff line change
Expand Up @@ -78,8 +78,8 @@ to it explicitly using ``self``:
a = self
a.x = 1 # Error: 'x' not defined

Annotating ``__init__`` methods
*******************************
Annotating __init__ methods
***************************

The :py:meth:`__init__ <object.__init__>` method is somewhat special -- it doesn't return a
value. This is best expressed as ``-> None``. However, since many feel
Expand Down
17 changes: 8 additions & 9 deletions docs/source/error_code_list.rst
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ definition in an active scope, such as an assignment, function
definition or an import. This can catch missing definitions, missing
imports, and typos.

This example accidentally calls ``sort()`` instead of ``sorted()``:
This example accidentally calls ``sort()`` instead of :py:func:`sorted`:

.. code-block:: python

Expand Down Expand Up @@ -181,7 +181,7 @@ This example incorrectly uses the function ``log`` as a type:
for x in objs:
f(x)

You can use ``Callable`` as the type for callable objects:
You can use :py:data:`~typing.Callable` as the type for callable objects:

.. code-block:: python

Expand Down Expand Up @@ -418,8 +418,8 @@ Example:
Check TypedDict items [typeddict-item]
--------------------------------------

When constructing a TypedDict object, mypy checks that each key and value is compatible
with the TypedDict type that is inferred from the surrounding context.
When constructing a ``TypedDict`` object, mypy checks that each key and value is compatible
with the ``TypedDict`` type that is inferred from the surrounding context.

Example:

Expand Down Expand Up @@ -542,8 +542,7 @@ Check instantiation of abstract classes [abstract]

Mypy generates an error if you try to instantiate an abstract base
class (ABC). An abtract base class is a class with at least one
abstract method or attribute. (See also :doc:`Python
abc module documentation <python:library/abc>`)
abstract method or attribute. (See also :py:mod:`abc` module documentation)

Sometimes a class is made accidentally abstract, often due to an
unimplemented abstract method. In a case like this you need to provide
Expand Down Expand Up @@ -572,7 +571,7 @@ Example:
Check the target of NewType [valid-newtype]
-------------------------------------------

The target of a ``NewType`` definition must be a class type. It can't
The target of a :py:func:`NewType <typing.NewType>` definition must be a class type. It can't
be a union type, ``Any``, or various other special types.

You can also get this error if the target has been imported from a
Expand All @@ -596,10 +595,10 @@ for more information.
Check the return type of __exit__ [exit-return]
-----------------------------------------------

If mypy can determine that ``__exit__`` always returns ``False``, mypy
If mypy can determine that :py:meth:`__exit__ <object.__exit__>` always returns ``False``, mypy
checks that the return type is *not* ``bool``. The boolean value of
the return type affects which lines mypy thinks are reachable after a
``with`` statement, since any ``__exit__`` method that can return
``with`` statement, since any :py:meth:`__exit__ <object.__exit__>` method that can return
``True`` may swallow exceptions. An imprecise return type can result
in mysterious errors reported near ``with`` statements.

Expand Down
16 changes: 8 additions & 8 deletions docs/source/extending_mypy.rst
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,8 @@ what normally would have been the command line arguments to mypy.

Function ``run`` returns a ``Tuple[str, str, int]``, namely
``(<normal_report>, <error_report>, <exit_status>)``, in which ``<normal_report>``
is what mypy normally writes to ``sys.stdout``, ``<error_report>`` is what mypy
normally writes to ``sys.stderr`` and ``exit_status`` is the exit status mypy normally
is what mypy normally writes to :py:data:`sys.stdout`, ``<error_report>`` is what mypy
normally writes to :py:data:`sys.stderr` and ``exit_status`` is the exit status mypy normally
returns to the operating system.

A trivial example of using the api is the following
Expand Down Expand Up @@ -98,7 +98,7 @@ High-level overview
*******************

Every entry point function should accept a single string argument
that is a full mypy version and return a subclass of ``mypy.plugins.Plugin``:
Copy link
Contributor Author

Choose a reason for hiding this comment

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

One of two changes in this PR that are not related to referencing, typo fix.

that is a full mypy version and return a subclass of ``mypy.plugin.Plugin``:

.. code-block:: python

Expand Down Expand Up @@ -174,7 +174,7 @@ For example:
instead of module level functions.

**get_method_signature_hook()** is used to adjust the signature of a method.
This includes special Python methods except ``__init__()`` and ``__new__()``.
This includes special Python methods except :py:meth:`~object.__init__` and :py:meth:`~object.__new__`.
For example in this code:

.. code-block:: python
Expand All @@ -185,12 +185,12 @@ For example in this code:
x[0] = 42

mypy will call ``get_method_signature_hook("ctypes.Array.__setitem__")``
so that the plugin can mimic the ``ctypes`` auto-convert behavior.
so that the plugin can mimic the :py:mod:`ctypes` auto-convert behavior.

**get_attribute_hook** overrides instance member field lookups and property
**get_attribute_hook()** overrides instance member field lookups and property
Copy link
Contributor Author

Choose a reason for hiding this comment

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

All other paragraphs use parentheses in hook names, I suppose they were omitted by mistake here.

Copy link
Member

Choose a reason for hiding this comment

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

+1

access (not assignments, and not method calls). This hook is only called for
fields which already exist on the class. *Exception:* if ``__getattr__`` or
``__getattribute__`` is a method on the class, the hook is called for all
fields which already exist on the class. *Exception:* if :py:meth:`__getattr__ <object.__getattr__>` or
:py:meth:`__getattribute__ <object.__getattribute__>` is a method on the class, the hook is called for all
fields which do not refer to methods.

**get_class_decorator_hook()** can be used to update class definition for
Expand Down
9 changes: 4 additions & 5 deletions docs/source/faq.rst
Original file line number Diff line number Diff line change
Expand Up @@ -110,17 +110,16 @@ 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 ``Iterable`` that always support structural subtyping). Here are some
such as :py:class:`~typing.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
using type inference.

2. Python provides built-in support for nominal ``isinstance()`` tests and
2. Python provides built-in support for nominal :py:func:`isinstance` tests and
they are widely used in programs. Only limited support for structural
``isinstance()`` is available, and it's less type safe than
nominal type tests.
:py:func:`isinstance` is available, and it's less type safe than nominal type tests.

3. Many programmers are already familiar with static, nominal subtyping and it
has been successfully used in languages such as Java, C++ and
Expand Down Expand Up @@ -164,7 +163,7 @@ monkey patching of methods.
How is mypy different from Cython?
**********************************

`Cython :doc:<cython:index>` is a variant of Python that supports
:doc:`Cython <cython:index>` is a variant of Python that supports
Copy link
Contributor Author

Choose a reason for hiding this comment

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

Fixing my own errors here. No idea why Sphinx didn't catch this on build.

Copy link
Member

Choose a reason for hiding this comment

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

Didn't you have to run it with special flags to check errors?

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 did (using sphinx-build -WEan), however Sphinx ignores markup errors and just renders the text as-is. Neither does doc8 nor restructuredtext-lint, sadly.

compilation to CPython C modules. It can give major speedups to
certain classes of programs compared to CPython, and it provides
static typing (though this is different from mypy). Mypy differs in
Expand Down
14 changes: 7 additions & 7 deletions docs/source/final_attrs.rst
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ from being overridden in a subclass:
class ListView(Window):
BORDER_WIDTH = 3 # Error: can't override a final attribute

You can use ``@property`` to make an attribute read-only, but unlike ``Final``,
You can use :py:class:`@property <property>` to make an attribute read-only, but unlike ``Final``,
it doesn't work with module attributes, and it doesn't prevent overriding in
subclasses.

Expand Down Expand Up @@ -83,11 +83,11 @@ You can use ``Final`` in one of these forms:

* Finally, you can write ``self.id: Final = 1`` (also optionally with
a type in square brackets). This is allowed *only* in
``__init__`` methods, so that the final instance attribute is
:py:meth:`__init__ <object.__init__>` methods, so that the final instance attribute is
assigned only once when an instance is created.

Details of using Final
**********************
Details of using ``Final``
**************************

These are the two main rules for defining a final name:

Expand All @@ -98,7 +98,7 @@ These are the two main rules for defining a final name:
* There must be *exactly one* assignment to a final name.

A final attribute declared in a class body without an initializer must
be initialized in the ``__init__`` method (you can skip the
be initialized in the :py:meth:`__init__ <object.__init__>` method (you can skip the
initializer in stub files):

.. code-block:: python
Expand All @@ -121,9 +121,9 @@ annotations. Using it in any other position is an error. In particular,
def fun(x: Final[List[int]]) -> None: # Error!
...

``Final`` and ``ClassVar`` should not be used together. Mypy will infer
``Final`` and :py:data:`~typing.ClassVar` should not be used together. Mypy will infer
the scope of a final declaration automatically depending on whether it was
initialized in the class body or in ``__init__``.
initialized in the class body or in :py:meth:`__init__ <object.__init__>`.

A final attribute can't be overridden by a subclass (even with another
explicit final declaration). Note however that a final attribute can
Expand Down
28 changes: 14 additions & 14 deletions docs/source/getting_started.rst
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ Getting started
===============

This chapter introduces some core concepts of mypy, including function
annotations, the ``typing`` module, library stubs, and more.
annotations, the :py:mod:`typing` module, library stubs, and more.

Be sure to read this chapter carefully, as the rest of the documentation
may not make much sense otherwise.
Expand Down Expand Up @@ -167,9 +167,9 @@ So far, we've added type hints that use only basic concrete types like
``str`` and ``float``. What if we want to express more complex types,
such as "a list of strings" or "an iterable of ints"?

You can find many of these more complex static types inside of the ``typing``
You can find many of these more complex static types inside of the :py:mod:`typing`
module. For example, to indicate that some function can accept a list of
strings, use the ``List`` type from the ``typing`` module:
Copy link
Contributor Author

Choose a reason for hiding this comment

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

Second change unrelated to referencing. IMO with the List reference, there's no need to mention the module again - it's also referenced one line above that. What do you think?

Copy link
Member

Choose a reason for hiding this comment

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

+1

(PS. When commenting on a diff chunk, please attach the comment to the last line, so the context in email or in the Conversation view is clearer. I think you can now also shift-click to attach a comment to a range of lines.)

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Got it!

strings, use the :py:class:`~typing.List` type:

.. code-block:: python

Expand All @@ -185,16 +185,16 @@ strings, use the ``List`` type from the ``typing`` module:
greet_all(names) # Ok!
greet_all(ages) # Error due to incompatible types

The ``List`` type is an example of something called a *generic type*: it can
accept one or more *type parameters*. In this case, we *parameterized* ``List``
The :py:class:`~typing.List` type is an example of something called a *generic type*: it can
accept one or more *type parameters*. In this case, we *parameterized* :py:class:`~typing.List`
by writing ``List[str]``. This lets mypy know that ``greet_all`` accepts specifically
lists containing strings, and not lists containing ints or any other type.

In this particular case, the type signature is perhaps a little too rigid.
After all, there's no reason why this function must accept *specifically* a list --
it would run just fine if you were to pass in a tuple, a set, or any other custom iterable.

You can express this idea using the ``Iterable`` type instead of ``List``:
You can express this idea using the :py:class:`~typing.Iterable` type instead of :py:class:`~typing.List`:

.. code-block:: python

Expand All @@ -205,7 +205,7 @@ You can express this idea using the ``Iterable`` type instead of ``List``:
print('Hello ' + name)

As another example, suppose you want to write a function that can accept *either*
ints or strings, but no other types. You can express this using the ``Union`` type:
ints or strings, but no other types. You can express this using the :py:data:`~typing.Union` type:

.. code-block:: python

Expand All @@ -217,8 +217,8 @@ ints or strings, but no other types. You can express this using the ``Union`` ty
else:
return user_id

Similarly, suppose that you want the function to accept only strings or None. You can
again use ``Union`` and use ``Union[str, None]`` -- or alternatively, use the type
Similarly, suppose that you want the function to accept only strings or ``None``. You can
again use :py:data:`~typing.Union` and use ``Union[str, None]`` -- or alternatively, use the type
``Optional[str]``. These two types are identical and interchangeable: ``Optional[str]``
is just a shorthand or *alias* for ``Union[str, None]``. It exists mostly as a convenience
to help function signatures look a little cleaner:
Expand All @@ -233,7 +233,7 @@ to help function signatures look a little cleaner:
name = 'stranger'
return 'Hello, ' + name

The ``typing`` module contains many other useful types. You can find a
The :py:mod:`typing` module contains many other useful types. You can find a
quick overview by looking through the :ref:`mypy cheatsheets <overview-cheat-sheets>`
and a more detailed overview (including information on how to make your own
generic types or your own type aliases) by looking through the
Expand All @@ -243,8 +243,8 @@ One final note: when adding types, the convention is to import types
using the form ``from typing import Iterable`` (as opposed to doing
just ``import typing`` or ``import typing as t`` or ``from typing import *``).

For brevity, we often omit these ``typing`` imports in code examples, but
mypy will give an error if you use types such as ``Iterable``
For brevity, we often omit these :py:mod:`typing` imports in code examples, but
mypy will give an error if you use types such as :py:class:`~typing.Iterable`
without first importing them.

Local type inference
Expand All @@ -255,7 +255,7 @@ mypy will automatically type check that function's body. While doing so,
mypy will try and *infer* as many details as possible.

We saw an example of this in the ``normalize_id`` function above -- mypy understands
basic ``isinstance`` checks and so can infer that the ``user_id`` variable was of
basic :py:func:`isinstance <isinstance>` checks and so can infer that the ``user_id`` variable was of
type ``int`` in the if-branch and of type ``str`` in the else-branch. Similarly, mypy
was able to understand that ``name`` could not possibly be ``None`` in the ``greeting``
function above, based both on the ``name is None`` check and the variable assignment
Expand Down Expand Up @@ -315,7 +315,7 @@ For example, consider this code:
x = chr(4)

Without a library stub, mypy would have no way of inferring the type of ``x``
and checking that the argument to ``chr`` has a valid type.
and checking that the argument to :py:func:`chr` has a valid type.

Mypy complains if it can't find a stub (or a real module) for a
library module that you import. Some modules ship with stubs that mypy
Expand Down
4 changes: 2 additions & 2 deletions docs/source/protocols.rst
Original file line number Diff line number Diff line change
Expand Up @@ -376,8 +376,8 @@ such as trees and linked lists:

root: TreeLike = SimpleTree(0) # OK

Using ``isinstance()`` with protocols
*************************************
Using isinstance() with protocols
*********************************

You can use a protocol class with ``isinstance()`` if you decorate it
with the ``@runtime_checkable`` class decorator. The decorator adds
Expand Down