Skip to content

Added example in the doc for TypeVar in using generic classes #8573

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 3 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
38 changes: 38 additions & 0 deletions docs/source/common_issues.rst
Original file line number Diff line number Diff line change
Expand Up @@ -595,6 +595,44 @@ string literal types or :py:data:`~typing.TYPE_CHECKING`:

results: 'Queue[int]' = Queue() # OK

If you use a type variable in the type alias that is used as a base class and
implement it in above way, it will give error. Note that type arguments are only
required when using `--disallow-any-generics` (or `--strict`). However, this will
still be a problem even if these options aren't enabled, since we want to make the
subclass generic (otherwise it would be pretty pointless to use a type variable),
and this would result in a runtime error without the suggested trick.

.. code-block:: python

from queue import Queue
from typing import TYPE_CHECKING, TypeVar

_T = TypeVar("_T")
if TYPE_CHECKING:
MyQueueBase = Queue[_T]
else:
MyQueueBase = Queue

class MyQueue(MyQueueBase): pass # error: Missing type parameters for generic type

Note here that this error only comes when some configuration options are enabled.
To avoid this problem, we need to create another class in the hierarchy which makes
use of :py:data:`~typing.Generic` when :py:data:`~typing.TYPE_CHECKING` is disabled
and behaves normally when :py:data:`~typing.TYPE_CHECKING` is enabled.

.. code-block:: python

from queue import Queue
from typing import TYPE_CHECKING, TypeVar, Generic

_T = TypeVar("_T")
if TYPE_CHECKING:
class MyQueueBase(Queue[_T]): pass
else:
class MyQueueBase(Generic[_T], Queue): pass

class MyQueue(MyQueueBase[_T]): pass # OK

If you are running Python 3.7+ you can use ``from __future__ import annotations``
as a (nicer) alternative to string quotes, read more in :pep:`563`. For example:

Expand Down