python generic type code example
Example 1: python template generics
from typing import TypeVar, Generic
T = TypeVar('T')
class Stack(Generic[T]):
def __init__(self) -> None:
self.items: List[T] = []
def push(self, item: T) -> None:
self.items.append(item)
def pop(self) -> T:
return self.items.pop()
def empty(self) -> bool:
return not self.items
Example 2: python optional type annotation
from custom_module import SomeClass
from typing import Optional
class SubClass:
a_reference: Optional[SomeClass]
def __init__(self):
self.a_reference = None