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?
CodePudding user response:
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.
CodePudding user response:
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]):
...