Generic class internals

You may wonder what happens at runtime when you indexStack. Actually, indexing Stack returns essentially a copyof Stack that returns instances of the original class oninstantiation:

  1. >>> print(Stack)
  2. __main__.Stack
  3. >>> print(Stack[int])
  4. __main__.Stack[int]
  5. >>> print(Stack[int]().__class__)
  6. __main__.Stack

Note that built-in types list, dict and so on do not supportindexing in Python. This is why we have the aliases List, Dictand so on in the typing module. Indexing these aliases givesyou a class that directly inherits from the target class in Python:

  1. >>> from typing import List
  2. >>> List[int]
  3. typing.List[int]
  4. >>> List[int].__bases__
  5. (<class 'list'>, typing.MutableSequence)

Generic types could be instantiated or subclassed as usual classes,but the above examples illustrate that type variables are erased atruntime. Generic Stack instances are just ordinaryPython objects, and they have no extra runtime overhead or magic dueto being generic, other than a metaclass that overloads the indexingoperator.