Clarify what's allowed in the base classes when making a new generic class.

This commit is contained in:
Guido van Rossum 2016-03-22 08:56:19 -07:00
parent db9caac261
commit cf6962bc20
1 changed files with 25 additions and 1 deletions

View File

@ -403,15 +403,39 @@ thus invalid::
class Pair(Generic[T, T]): # INVALID class Pair(Generic[T, T]): # INVALID
... ...
The ``Generic[T]`` base class is redundant in simple cases where you
subclass some other generic class and specify type variables for its
parameters::
from typing import TypeVar, Iterator
T = TypeVar('T')
class MyIter(Iterator[T]):
...
That class definition is equivalent to::
class MyIter(Iterator[T], Generic[T]):
...
You can use multiple inheritance with ``Generic``:: You can use multiple inheritance with ``Generic``::
from typing import TypeVar, Generic, Sized from typing import TypeVar, Generic, Sized, Iterable, Container, Tuple
T = TypeVar('T') T = TypeVar('T')
class LinkedList(Sized, Generic[T]): class LinkedList(Sized, Generic[T]):
... ...
K = TypeVar('K')
V = TypeVar('V')
class MyMapping(Iterable[Tuple[K, V]],
Container[Tuple[K, V]],
Generic[K, V]):
...
Subclassing a generic class without specifying type parameters assumes Subclassing a generic class without specifying type parameters assumes
``Any`` for each position. In the following example, ``MyIterable`` ``Any`` for each position. In the following example, ``MyIterable``
is not generic but implicitly inherits from ``Iterable[Any]``:: is not generic but implicitly inherits from ``Iterable[Any]``::