snippetpythonModeratepending
Python typing patterns for everyday use
Viewed 0 times
type hintstypinggenericcallabletypevarmypy
Problem
Need practical type annotation patterns for common Python code: generics, unions, callables, overloads.
Solution
Everyday Python typing patterns:
from typing import TypeVar, Generic, Callable, Literal, TypeAlias
from collections.abc import Sequence, Mapping, Iterator
# Basic annotations (Python 3.10+ syntax)
def greet(name: str, excited: bool = False) -> str:
return f'Hello {name}{"!" if excited else "."}'
# Union types (Python 3.10+)
def process(value: int | str | None) -> str:
if value is None:
return 'nothing'
return str(value)
# Collections
def summarize(items: list[str], counts: dict[str, int]) -> None: ...
# Callable types
def apply(func: Callable[[int, int], float], a: int, b: int) -> float:
return func(a, b)
# Generic functions
T = TypeVar('T')
def first(items: Sequence[T]) -> T | None:
return items[0] if items else None
# Generic class
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()
stack: Stack[int] = Stack()
stack.push(42) # OK
# Literal types
def set_mode(mode: Literal['read', 'write', 'append']) -> None: ...
# Type alias
JSON: TypeAlias = dict[str, 'JSON'] | list['JSON'] | str | int | float | bool | None
# TypedDict for structured dicts
from typing import TypedDict
class UserDict(TypedDict):
name: str
age: int
email: str | None
def create_user(data: UserDict) -> None:
print(data['name']) # Type-safe key access
# Self type (Python 3.11+)
from typing import Self
class Builder:
def set_name(self, name: str) -> Self:
self.name = name
return selfWhy
Type hints catch bugs before runtime, enable better IDE support, and serve as documentation. Modern Python (3.10+) syntax makes them concise.
Context
Python projects using type annotations
Revisions (0)
No revisions yet.