Skip to content

Commit 6ac3196

Browse files
committed
Incorporate additional rules suggested by @erictraut.
1 parent 59198a1 commit 6ac3196

File tree

1 file changed

+38
-2
lines changed

1 file changed

+38
-2
lines changed

docs/spec/generics.rst

Lines changed: 38 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -166,8 +166,44 @@ thus invalid::
166166
class Pair(Generic[T, T]): # INVALID
167167
...
168168

169-
When no ``Generic[T]`` or ``Protocol[T]`` base class is present, a defined
170-
class is generic if you subclass one or more other generic classes and
169+
All arguments to ``Generic`` or ``Protocol`` must be type variables::
170+
171+
from typing import Generic, Protocol
172+
173+
class Bad1(Generic[int]): # INVALID
174+
...
175+
class Bad2(Protocol[int]): # INVALID
176+
...
177+
178+
When a ``Generic`` or parameterized ``Protocol`` base class is present, all type
179+
parameters for the class must appear within the ``Generic`` or
180+
``Protocol`` type argument list, respectively. A type checker should report an
181+
error if a type variable that is not included in the type argument list appears
182+
elsewhere in the base class list::
183+
184+
from typing import Generic, Protocol, TypeVar
185+
from collections.abc import Iterable
186+
187+
T = TypeVar('T')
188+
S = TypeVar('S')
189+
190+
class Bad1(Iterable[T], Generic[S]): # INVALID
191+
...
192+
class Bad2(Iterable[T], Protocol[S]): # INVALID
193+
...
194+
195+
Note that the above rule does not apply to a bare ``Protocol`` base class. This
196+
is valid (see below)::
197+
198+
from typing import Protocol, TypeVar
199+
from collections.abc import Iterator
200+
201+
T = TypeVar('T')
202+
203+
class MyIterator(Iterator[T], Protocol): ...
204+
205+
When no ``Generic`` or parameterized ``Protocol`` base class is present, a
206+
defined class is generic if you subclass one or more other generic classes and
171207
specify type variables for their parameters. See :ref:`generic-base-classes`
172208
for details.
173209

0 commit comments

Comments
 (0)