Skip to content

Commit eeb7393

Browse files
author
Guido van Rossum
committed
Clarify some rules around using or omitting Generic[...] as base class, by example.
1 parent 3b86719 commit eeb7393

File tree

1 file changed

+25
-1
lines changed

1 file changed

+25
-1
lines changed

pep-0484.txt

+25-1
Original file line numberDiff line numberDiff line change
@@ -403,15 +403,39 @@ thus invalid::
403403
class Pair(Generic[T, T]): # INVALID
404404
...
405405

406+
The ``Generic[T]`` base class is redundant in simple cases where you
407+
subclass some other generic class and specify type variables for its
408+
parameters::
409+
410+
from typing import TypeVar, Iterator
411+
412+
T = TypeVar('T')
413+
414+
class MyIter(Iterator[T]):
415+
...
416+
417+
That class definition is equivalent to::
418+
419+
class MyIter(Iterator[T], Generic[T]):
420+
...
421+
406422
You can use multiple inheritance with ``Generic``::
407423

408-
from typing import TypeVar, Generic, Sized
424+
from typing import TypeVar, Generic, Sized, Iterable, Container
409425

410426
T = TypeVar('T')
411427

412428
class LinkedList(Sized, Generic[T]):
413429
...
414430

431+
K = TypeVar('K')
432+
V = TypeVar('V')
433+
434+
class MyMapping(Iterable[Tuple[K, V]],
435+
Container[Iterable[K, V]],
436+
Generic[K, V]):
437+
...
438+
415439
Subclassing a generic class without specifying type parameters assumes
416440
``Any`` for each position. In the following example, ``MyIterable``
417441
is not generic but implicitly inherits from ``Iterable[Any]``::

0 commit comments

Comments
 (0)