Skip to content

Document variance change in subclasses #3179

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

Closed
wants to merge 2 commits into from
Closed
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
31 changes: 31 additions & 0 deletions docs/source/generics.rst
Original file line number Diff line number Diff line change
Expand Up @@ -370,6 +370,37 @@ type variables defined with special keyword arguments ``covariant`` or
my_box = Box(Cat())
look_into(my_box) # OK, but mypy would complain here for an invariant type

Note that the only change permitted in the variance of the generic class type
variable as you move down the inheritance hierarchy is from covariant or
contravariant to invariant. For example, this is valid:

.. code-block:: python

from typing import Generic, TypeVar

K_co = TypeVar('K_co', covariant=True)
class MultisetCo(Generic[K_co]):
def choose_random_item(self) -> K_co: ...

K = TypeVar('K')
class Multiset(Generic[K], MultisetCo[K]):
def count(self, key: K) -> int: ...

The following is not valid simply because ``choose_random_item`` does not
allow contravariance:

.. code-block:: python

from typing import Generic, TypeVar

K_co = TypeVar('K_co', covariant=True)
class MultisetCo(Generic[K_co]):
def choose_random_item(self) -> K_co: ...

K_contra = TypeVar('K_contra', contravariant=True)
class MultisetContra(Generic[K_contra], MultisetCo[K_contra]):
def count(self, key: K) -> int: ...

.. _type-variable-value-restriction:

Type variables with value restriction
Expand Down