Skip to content

Commit

Permalink
Docs: Use PEP 585 syntax in "The type of class objects" (#12516)
Browse files Browse the repository at this point in the history
  • Loading branch information
AlexWaygood committed Apr 16, 2022
1 parent ce858a6 commit 10ba5c1
Showing 1 changed file with 8 additions and 7 deletions.
15 changes: 8 additions & 7 deletions docs/source/kinds_of_types.rst
Original file line number Diff line number Diff line change
Expand Up @@ -615,10 +615,11 @@ The type of class objects
<484#the-type-of-class-objects>`.)

Sometimes you want to talk about class objects that inherit from a
given class. This can be spelled as :py:class:`Type[C] <typing.Type>` where ``C`` is a
given class. This can be spelled as ``type[C]`` (or, on Python 3.8 and lower,
:py:class:`typing.Type[C] <typing.Type>`) where ``C`` is a
class. In other words, when ``C`` is the name of a class, using ``C``
to annotate an argument declares that the argument is an instance of
``C`` (or of a subclass of ``C``), but using :py:class:`Type[C] <typing.Type>` as an
``C`` (or of a subclass of ``C``), but using ``type[C]`` as an
argument annotation declares that the argument is a class object
deriving from ``C`` (or ``C`` itself).

Expand Down Expand Up @@ -649,7 +650,7 @@ you pass it the right class object:
# (Here we could write the user object to a database)
return user
How would we annotate this function? Without :py:class:`~typing.Type` the best we
How would we annotate this function? Without the ability to parameterize ``type``, the best we
could do would be:

.. code-block:: python
Expand All @@ -665,14 +666,14 @@ doesn't see that the ``buyer`` variable has type ``ProUser``:
buyer = new_user(ProUser)
buyer.pay() # Rejected, not a method on User
However, using :py:class:`~typing.Type` and a type variable with an upper bound (see
However, using the ``type[C]`` syntax and a type variable with an upper bound (see
:ref:`type-variable-upper-bound`) we can do better:

.. code-block:: python
U = TypeVar('U', bound=User)
def new_user(user_class: Type[U]) -> U:
def new_user(user_class: type[U]) -> U:
# Same implementation as before
Now mypy will infer the correct type of the result when we call
Expand All @@ -685,12 +686,12 @@ Now mypy will infer the correct type of the result when we call
.. note::

The value corresponding to :py:class:`Type[C] <typing.Type>` must be an actual class
The value corresponding to ``type[C]`` must be an actual class
object that's a subtype of ``C``. Its constructor must be
compatible with the constructor of ``C``. If ``C`` is a type
variable, its upper bound must be a class object.

For more details about ``Type[]`` see :pep:`PEP 484: The type of
For more details about ``type[]`` and :py:class:`typing.Type[] <typing.Type>`, see :pep:`PEP 484: The type of
class objects <484#the-type-of-class-objects>`.

.. _text-and-anystr:
Expand Down

0 comments on commit 10ba5c1

Please sign in to comment.