Using classes that are generic in stubs but not at runtime

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

  1. from queue import Queue
  2.  
  3. class Tasks(Queue[str]): # TypeError: 'type' object is not subscriptable
  4. ...
  5.  
  6. results: Queue[int] = Queue() # TypeError: 'type' object is not subscriptable

To avoid these errors while still having precise types you can either usestring literal types or TYPE_CHECKING:

  1. from queue import Queue
  2. from typing import TYPE_CHECKING
  3.  
  4. if TYPE_CHECKING:
  5. BaseQueue = Queue[str] # this is only processed by mypy
  6. else:
  7. BaseQueue = Queue # this is not seen by mypy but will be executed at runtime.
  8.  
  9. class Tasks(BaseQueue): # OK
  10. ...
  11.  
  12. results: 'Queue[int]' = Queue() # OK

If you are running Python 3.7+ you can use from future import annotationsas a (nicer) alternative to string quotes, read more in PEP 563. For example:

  1. from __future__ import annotations
  2. from queue import Queue
  3.  
  4. results: Queue[int] = Queue() # This works at runtime