Skip to content

Commit 9a578fa

Browse files
ilevkivskyiJukkaL
authored andcommitted
Add docummentation on generic subclasses (#2821)
1 parent 04f9bc1 commit 9a578fa

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed

docs/source/generics.rst

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -99,6 +99,61 @@ Python objects, and they have no extra runtime overhead or magic due
9999
to being generic, other than a metaclass that overloads the indexing
100100
operator.
101101

102+
Defining sub-classes of generic classes
103+
***************************************
104+
105+
User defined generics and generics defined in typing module
106+
can be used as base classes for another classes, both generic and
107+
non-generic. For example:
108+
109+
.. code-block:: python
110+
111+
from typing import Generic, TypeVar, Iterable
112+
T = TypeVar('T')
113+
114+
class Stream(Iterable[T]): # This is a generic class
115+
...
116+
input: Stream[int]
117+
118+
class Codes(Iterable[int]): # This is not a generic class
119+
...
120+
output: Codes[int] # Error!
121+
122+
class Receiver(Generic[T]):
123+
def accept(self, value: T) -> None:
124+
...
125+
class AdvancedReceiver(Receiver[T]):
126+
...
127+
128+
Note that ``Generic[...]`` can be omitted from bases, if there are
129+
other generic classes. If you include ``Generic[...]`` in bases, then
130+
it should list all type variables present in other bases (or more,
131+
if needed). The order of type variables is defined by the following
132+
rules:
133+
134+
* If ``Generic[...]`` is present, then the order of variables is
135+
always determined by their order in ``Generic[...]``.
136+
* If there are no ``Generic[...]`` in bases, then all type variables
137+
are collected in the lexicographic order (i.e. by first appearance).
138+
139+
For example:
140+
141+
.. code-block:: python
142+
143+
from typing import Generic, TypeVar, Any
144+
T = TypeVar('T')
145+
S = TypeVar('S')
146+
U = TypeVar('U')
147+
148+
class One(Generic[T]): ...
149+
class Another(Generic[T]): ...
150+
151+
class First(One[T], Another[S]): ...
152+
class Second(One[T], Another[S], Generic[S, U, T]): ...
153+
154+
x: First[int, str] # Here T is bound to int, S is bound to str
155+
y: Second[int, str, Any] # Here T is Any, S is int, and U is str
156+
102157
.. _generic-functions:
103158

104159
Generic functions

0 commit comments

Comments
 (0)