Skip to content

Commit e8fc2fe

Browse files
authored
Improve type covariance documentation in typing.rst
1 parent 2498c22 commit e8fc2fe

File tree

1 file changed

+17
-7
lines changed

1 file changed

+17
-7
lines changed

Doc/library/typing.rst

Lines changed: 17 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -413,6 +413,7 @@ example::
413413
Note that ``type[C]`` is covariant::
414414

415415
class User: ...
416+
class BasicUser(User): ...
416417
class ProUser(User): ...
417418
class TeamUser(User): ...
418419

@@ -421,22 +422,31 @@ Note that ``type[C]`` is covariant::
421422
return user_class()
422423

423424
make_new_user(User) # OK
424-
make_new_user(ProUser) # Also OK: ``type[ProUser]`` is a subtype of ``type[User]``
425-
make_new_user(TeamUser) # Still fine
425+
make_new_user(BasicUser) # Also OK: ``type[BasicUser]`` is a subtype of ``type[User]``
426+
make_new_user(ProUser) # Still fine
427+
make_new_user(TeamUser) # Also fine
426428
make_new_user(User()) # Error: expected ``type[User]`` but got ``User``
427429
make_new_user(int) # Error: ``type[int]`` is not a subtype of ``type[User]``
428430

429431
The only legal parameters for :class:`type` are classes, :data:`Any`,
430432
:ref:`type variables <generics>`, and unions of any of these types.
431433
For example::
434+
class HeroUser(ProUser): ...
435+
class RegularUser(BasicUser): ...
436+
class ManagerUser(TeamUser): ...
432437

433438
def new_non_team_user(user_class: type[BasicUser | ProUser]): ...
434439

435-
new_non_team_user(BasicUser) # OK
436-
new_non_team_user(ProUser) # OK
437-
new_non_team_user(TeamUser) # Error: ``type[TeamUser]`` is not a subtype
438-
# of ``type[BasicUser | ProUser]``
439-
new_non_team_user(User) # Also an error
440+
new_non_team_user(BasicUser) # OK
441+
new_non_team_user(ProUser) # OK
442+
new_non_team_user(RegularUser) # OK
443+
new_non_team_user(HeroUser) # OK
444+
445+
new_non_team_user(ManagerUser) # Error: ``type[ManagerUser]`` is not a subtype
446+
# of ``type[BasicUser | ProUser]``
447+
new_non_team_user(TeamUser) # Error: ``type[TeamUser]`` is not a subtype
448+
# of ``type[BasicUser | ProUser]``
449+
new_non_team_user(User) # Also an error
440450

441451
``type[Any]`` is equivalent to :class:`type`, which is the root of Python's
442452
:ref:`metaclass hierarchy <metaclasses>`.

0 commit comments

Comments
 (0)