Middle
How to implement a generic in Python?
sobes.tech AI
Answer from AI
In Python, generics are implemented using the typing module, which appeared in the standard library. To create generic types, Generic and type parameters TypeVar are used. This allows writing functions and classes that work with different types while maintaining type hints.
Example:
from typing import TypeVar, Generic, List
T = TypeVar('T')
class Stack(Generic[T]):
def __init__(self):
self._items: List[T] = []
def push(self, item: T) -> None:
self._items.append(item)
def pop(self) -> T:
return self._items.pop()
stack_int = Stack[int]()
stack_int.push(1)
value = stack_int.pop() # value will be of type int
Thus, Stack is a generic class that can be used with any type.