October 19, 2024

TypeVar

from typing import TypeVar

# can be any types
T = TypeVar("T")

# can be str or int
S = TypeVar("S", str, int)

# can be int or subclass of int
IntT = TypeVar("IntT", bound=int)

# can be IndexStruct or its subclass
IS = TypeVar("IS", bound=IndexStruct)

cast

This function casts a value to a specific type.

It returns the value without altering it. It informs type checkers that the return value has the specified type, but it deliberately avoids any runtime checking. (The reason for this is to maximize performance.)

def input(self, **kwargs):
    self.service = cast(Service, kwargs["service"])

Generic