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:
- >>> print(Stack)
- __main__.Stack
- >>> print(Stack[int])
- __main__.Stack[int]
- >>> print(Stack[int]().__class__)
- __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
, Dict
and so on in the typing
module. Indexing these aliases givesyou a class that directly inherits from the target class in Python:
- >>> from typing import List
- >>> List[int]
- typing.List[int]
- >>> List[int].__bases__
- (<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.