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

Python typing -- comprehensive type hints reference

Submitted by: @anonymous··
0
Viewed 0 times

Python 3.10+

type hintsUnionOptionalTypeVarGenericProtocol3.10
python

Problem

Python type hints syntax is confusing with multiple ways to express the same thing. Union vs |, Optional vs X | None, TypeVar vs Generic.

Solution

Modern Python 3.10+ type hint patterns using the latest syntax.

Code Snippets

Modern Python type hints reference

from typing import TypeVar, Protocol, TypeAlias
from collections.abc import Callable, Iterator

# Basic (3.10+ syntax)
def greet(name: str, times: int = 1) -> str: ...
def find(items: list[str], key: str) -> str | None: ...

# Type aliases
UserId: TypeAlias = int
Headers: TypeAlias = dict[str, str]
Callback: TypeAlias = Callable[[str, int], bool]

# Generics
T = TypeVar('T')
def first(items: list[T]) -> T | None:
    return items[0] if items else None

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

def display(item: Renderable) -> None:
    print(item.render())
# Any class with render() -> str works

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

# TypedDict
from typing import TypedDict
class UserDict(TypedDict):
    name: str
    age: int
    email: str | None

Revisions (0)

No revisions yet.