Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 1de1a6a

Browse files
author
Guido van Rossum
committed
Issue #27905: Docs for typing.Type[C], by Michael Lee. (Merge 3.5->3.6)
2 parents 4b9abf3 + e848cd7 commit 1de1a6a

1 file changed

Lines changed: 39 additions & 0 deletions

File tree

Doc/library/typing.rst

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -502,6 +502,45 @@ The module defines the following classes, functions and decorators:
502502
except KeyError:
503503
return default
504504

505+
.. class:: Type
506+
507+
A variable annotated with ``C`` may accept a value of type ``C``. In
508+
contrast, a variable annotated with ``Type[C]`` may accept values that are
509+
classes themselves -- specifically, it will accept the *class object* of
510+
``C``. For example::
511+
512+
a = 3 # Has type 'int'
513+
b = int # Has type 'Type[int]'
514+
c = type(a) # Also has type 'Type[int]'
515+
516+
Note that ``Type[C]`` is covariant::
517+
518+
class User: ...
519+
class BasicUser(User): ...
520+
class ProUser(User): ...
521+
class TeamUser(User): ...
522+
523+
# Accepts User, BasicUser, ProUser, TeamUser, ...
524+
def make_new_user(user_class: Type[User]) -> User:
525+
# ...
526+
return user_class()
527+
528+
The fact that ``Type[C]`` is covariant implies that all subclasses of
529+
``C`` should implement the same constructor signature and class method
530+
signatures as ``C``. The type checker should flag violations of this,
531+
but should also allow constructor calls in subclasses that match the
532+
constructor calls in the indicated base class. How the type checker is
533+
required to handle this particular case may change in future revisions of
534+
PEP 484.
535+
536+
The only legal parameters for ``Type`` are classes, unions of classes, and
537+
``Any``. For example::
538+
539+
def new_non_team_user(user_class: Type[Union[BaseUser, ProUser]]): ...
540+
541+
``Type[Any]`` is equivalent to ``Type`` which in turn is equivalent
542+
to ``type``, which is the root of Python's metaclass hierarchy.
543+
505544
.. class:: Iterable(Generic[T_co])
506545

507546
A generic version of :class:`collections.abc.Iterable`.

0 commit comments

Comments
 (0)