Skip to content

Document what to do if a class is not generic at runtime #5833

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

Merged
merged 2 commits into from
Oct 25, 2018
Merged
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
35 changes: 35 additions & 0 deletions docs/source/common_issues.rst
Original file line number Diff line number Diff line change
Expand Up @@ -496,6 +496,41 @@ Here's the above example modified to use ``MYPY``:
return [arg]


Using classes that are generic in stubs but not at runtime
----------------------------------------------------------

Some classes are declared as generic in stubs, but not at runtime. Examples
in the standard library include ``os.PathLike`` and ``queue.Queue``.
Subscripting such a class will result in a runtime error:

.. code-block:: python

from queue import Queue

class Tasks(Queue[str]): # TypeError: 'type' object is not subscriptable
...

results: Queue[int] = Queue() # TypeError: 'type' object is not subscriptable

To avoid these errors while still having precise types you can either use
string literal types or ``typing.TYPE_CHECKING``:

.. code-block:: python

from queue import Queue
from typing import TYPE_CHECKING

if TYPE_CHECKING:
BaseQueue = Queue[str] # this is only processed by mypy
else:
BaseQueue = Queue # this is not seen by mypy but will be executed at runtime.

class Tasks(BaseQueue): # OK
...

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


.. _silencing-linters:

Silencing linters
Expand Down