RecentlyOdds & Ends
now playing

Python Generic and TypeVar

Together, Generic and TypeVar enable templating in Python. TypeVar declares a placeholder type variable; Generic uses it in a class.

The following code blocks are equivalent.

T = TypeVar("T")

class MyClass(Generic[T]):
  _thingy: T | None
template<typename T>
class MyClass {
  T* _thingy;
}

Binding TypeVar

You can do T = TypeVar(“T”, bound=MyBaseClass) to enforce that T is the base class type or whatever

Using generics with abstract base classes

Generics and abstract base classes are often used together. The following code says: “This can be used with any type, but whatever type it is must implement these methods.” You get the flexibility of generics and the guarantees of the abstract base class.

T = TypeVar("T")

class MyClass(ABC, Generic[T]):
  _thingy: T | None

  def class_method(self):
    # Virtual method
    ...