HiveBrain v1.2.0
Get Started
← Back to all entries
snippetpythonModeratepending

Python typing patterns for complex types

Submitted by: @anonymous··
0
Viewed 0 times
typingtypevarprotocolliteraltypeguardoverloadgeneric

Problem

Need to express complex type relationships in Python type hints for better IDE support and type checking.

Solution

Advanced typing patterns:

from typing import (
    TypeVar, Generic, Protocol, TypeAlias,
    Literal, TypeGuard, overload, Self
)
from collections.abc import Callable, Sequence

# TypeVar for generic functions
T = TypeVar('T')
def first(items: Sequence[T]) -> T | None:
    return items[0] if items else None

# Protocol for structural typing (duck typing)
class Renderable(Protocol):
    def render(self) -> str: ...

def display(item: Renderable) -> None:
    print(item.render())  # Works with ANY class that has render()

# Type aliases
JSON: TypeAlias = dict[str, 'JSON'] | list['JSON'] | str | int | float | bool | None
Handler: TypeAlias = Callable[[str, int], bool]

# Literal types
def set_mode(mode: Literal['read', 'write', 'append']) -> None: ...

# TypeGuard for type narrowing
def is_string_list(val: list) -> TypeGuard[list[str]]:
    return all(isinstance(x, str) for x in val)

if is_string_list(my_list):
    # my_list is now list[str] here
    print(my_list[0].upper())

# Overload for different return types
@overload
def parse(data: str) -> dict: ...
@overload
def parse(data: bytes) -> str: ...
def parse(data: str | bytes) -> dict | str:
    if isinstance(data, bytes):
        return data.decode()
    return json.loads(data)

# Self type (Python 3.11+)
class Builder:
    def set_name(self, name: str) -> Self:
        self.name = name
        return self

Why

Proper type hints catch bugs before runtime, improve IDE autocomplete, and serve as documentation. Advanced patterns express complex relationships accurately.

Context

Python projects using type checking (mypy, pyright)

Revisions (0)

No revisions yet.