pythonintermediate
Type Hints with Generics
Use Python generics for type-safe reusable data structures and functions.
pythonPress ⌘/Ctrl + Shift + C to copy
from typing import TypeVar, Generic, Optional
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:
if not self._items:
raise IndexError("Stack is empty")
return self._items.pop()
def peek(self) -> Optional[T]:
return self._items[-1] if self._items else None
def __len__(self) -> int:
return len(self._items)
# Type-safe usage
int_stack: Stack[int] = Stack()
int_stack.push(42)
int_stack.push(99)
print(int_stack.pop()) # 99
str_stack: Stack[str] = Stack()
str_stack.push("hello")
print(str_stack.peek()) # helloUse Cases
- Reusable data structures
- Type-safe collections
- Library design
Tags
Related Snippets
Similar patterns you can reuse in the same workflow.
pythonadvanced
Python Advanced Typing Patterns
Advanced type hints with Protocol, TypeVar, Generic, overload, and TypeGuard for safer code.
Best for: Building type-safe generic containers
#python#typing
pythonbeginner
Dataclass with Validation
Python dataclass with __post_init__ field validation, type coercion, and descriptive error messages.
Best for: Data transfer objects
#dataclass#validation
pythonintermediate
Python Dataclass Advanced Patterns
Advanced dataclass usage with validation, post-init processing, slots, and frozen instances.
Best for: Type-safe data models without ORMs
#python#dataclass
pythonadvanced
Protocol Classes for Structural Typing
Define interfaces with Protocol for duck-typing that works with static type checkers.
Best for: dependency injection
#python#protocol