Say I want to create a custom class and make use of contained type hinting like in list[int]. As I understand I would do that like:
from typing import Generic, TypeVar
T = TypeVar("T")
class MyContainer(Generic[T]):
def __init__(self, ls: list[T]):
pass
def __getitem__(self, ix: int) -> T:
pass
But does this now imply it’s a homogeneous container? Do I have to do anything special to use it like (c = MyContainer(['a', 1]))?
>Solution :
c = MyContainer(['a', 1]) doesn’t make any actual use of Generics (type is defaulted to Any). You need to pass type parameter for MyContainer, to tell what is the actual type variable to be used in place of T. For example:
c = MyContainer[str](['a', 1])
This will obviously trigger type checker to issue a warning:
Argument of type "list[str | int]" cannot be assigned to parameter "ls" of type "list[str]" in function "__init__"
"Literal[1]" is incompatible with "str"
So, now it’s a matter of correctly telling your class what you actually want to have in place of a type generic.
If you want to accept strings and ints but nothing else, typing it as:
c = MyContainer[str | int](['a', 1])
will work just fine.