@@ -615,10 +615,11 @@ The type of class objects
615
615
<484#the-type-of-class-objects >`.)
616
616
617
617
Sometimes you want to talk about class objects that inherit from a
618
- given class. This can be spelled as :py:class: `Type[C] <typing.Type> ` where ``C `` is a
618
+ given class. This can be spelled as ``type[C] `` (or, on Python 3.8 and lower,
619
+ :py:class: `typing.Type[C] <typing.Type> `) where ``C `` is a
619
620
class. In other words, when ``C `` is the name of a class, using ``C ``
620
621
to annotate an argument declares that the argument is an instance of
621
- ``C `` (or of a subclass of ``C ``), but using :py:class: ` Type [C] <typing.Type> ` as an
622
+ ``C `` (or of a subclass of ``C ``), but using `` type [C]` ` as an
622
623
argument annotation declares that the argument is a class object
623
624
deriving from ``C `` (or ``C `` itself).
624
625
@@ -649,7 +650,7 @@ you pass it the right class object:
649
650
# (Here we could write the user object to a database)
650
651
return user
651
652
652
- How would we annotate this function? Without :py:class: ` ~typing.Type ` the best we
653
+ How would we annotate this function? Without the ability to parameterize `` type ``, the best we
653
654
could do would be:
654
655
655
656
.. code-block :: python
@@ -665,14 +666,14 @@ doesn't see that the ``buyer`` variable has type ``ProUser``:
665
666
buyer = new_user(ProUser)
666
667
buyer.pay() # Rejected, not a method on User
667
668
668
- However, using :py:class: ` ~typing.Type ` and a type variable with an upper bound (see
669
+ However, using the `` type[C] `` syntax and a type variable with an upper bound (see
669
670
:ref: `type-variable-upper-bound `) we can do better:
670
671
671
672
.. code-block :: python
672
673
673
674
U = TypeVar(' U' , bound = User)
674
675
675
- def new_user (user_class : Type [U]) -> U:
676
+ def new_user (user_class : type [U]) -> U:
676
677
# Same implementation as before
677
678
678
679
Now mypy will infer the correct type of the result when we call
@@ -685,12 +686,12 @@ Now mypy will infer the correct type of the result when we call
685
686
686
687
.. note ::
687
688
688
- The value corresponding to :py:class: ` Type [C] <typing.Type> ` must be an actual class
689
+ The value corresponding to `` type [C]` ` must be an actual class
689
690
object that's a subtype of ``C ``. Its constructor must be
690
691
compatible with the constructor of ``C ``. If ``C `` is a type
691
692
variable, its upper bound must be a class object.
692
693
693
- For more details about ``Type [] `` see :pep: `PEP 484: The type of
694
+ For more details about ``type [] `` and :py:class: ` typing.Type[] <typing.Type> `, see :pep: `PEP 484: The type of
694
695
class objects <484#the-type-of-class-objects >`.
695
696
696
697
.. _text-and-anystr :
0 commit comments