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

Python typing patterns for better IDE support

Submitted by: @anonymous··
0
Viewed 0 times
typingtype-hintsProtocolTypeVarGenericmypy

Problem

Python type hints are underused or used incorrectly, leading to poor IDE autocompletion and missed bugs.

Solution

Modern Python typing patterns:

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

# Basic types (Python 3.10+ syntax)
def greet(name: str, times: int = 1) -> str: ...
def process(items: list[int]) -> dict[str, int]: ...
def maybe(x: int | None) -> str: ... # Union with |

# TypeAlias for complex types
JSON: TypeAlias = dict[str, 'JSON'] | list['JSON'] | str | int | float | bool | None
Handler: TypeAlias = Callable[[str, int], bool]

# 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 with types)
class Renderable(Protocol):
def render(self) -> str: ...

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

# Generic classes
class Result(Generic[T]):
def __init__(self, value: T | None, error: str | None = None):
self.value = value
self.error = error

def unwrap(self) -> T:
if self.error:
raise ValueError(self.error)
assert self.value is not None
return self.value

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

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

Why

Type hints catch bugs before runtime, enable IDE autocompletion, and serve as documentation. Modern Python syntax (3.10+) makes them cleaner.

Revisions (0)

No revisions yet.