How would I implement my own container with type hinting?

Question:

Say I want to make a container class MyContainer and I want to enable its use in type hints like def func(container: MyContainer[SomeType]), in a similar way to how I would be able to do def func(ls: list[SomeType]). How would I do that?

Asked By: Alexander Soare

||

Answers:

Use the Generic type with a TypeVar:

from typing import Generic, TypeVar

SomeType = TypeVar('SomeType')


class MyContainer(Generic[SomeType]):

    def add(self, item: SomeType):
        ...

Within the definition of MyContainer, SomeType is a placeholder for whatever type a particular MyContainer is declared to contain.

Answered By: Samwise

I guess you can define the class as a subclass similar to list, and define a generic type parameter using the TypeVar class from the typing module.

from typing import TypeVar, List

T = TypeVar('T')

class MyContainer(List[T]):
    pass

Now you can use MyContainer as a type hint.

def func(container: MyContainer[SomeType]):
    ...
Answered By: Phoenix
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.