python generics code example
Example 1: python template generics
from typing import TypeVar, Generic
T = TypeVar('T')
class Stack(Generic[T]):
def __init__(self) -> None:
# Create an empty list with items of type T
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 type constraint
# Example of typing constraint in python (From 3.5)
def greeting(name: str) -> str:
return 'Hello ' + name