Skip to content

Modern Typing

In many Python teams, typing is now a baseline assumption. Since Python 3.10, the syntax has become much more readable, which means typing is no longer just extra ceremony; it can actively improve API clarity.

Quick takeaway: modern typing is about readable primitives such as `X | Y`, `type` aliases, `Annotated`, `Literal`, `Self`, `Never`, and built-in generic syntax. These tools make API shape easier to express directly in code.

Quick Map of the Syntax

FeatureWhy it mattersExample
`XY`Much cleaner than Union[X, Y]
type aliasesMakes alias intent explicittype UserId = int
AnnotatedCarries type plus metadataAnnotated[int, Query(gt=0)]
LiteralConstrains allowed valuesLiteral["draft", "published"]
SelfImproves fluent and class-return APIsdef publish(self) -> Self
NeverMarks impossible return pathsdef fail() -> Never
built-in genericsKeeps syntax nativedict[str, int]

Practical Example

py
from typing import Annotated, Literal, Never, Self


type UserId = int
type Status = Literal["draft", "published"]


class Article:
    def __init__(self, title: str, status: Status = "draft") -> None:
        self.title = title
        self.status = status

    def publish(self) -> Self:
        self.status = "published"
        return self


def fail(message: str) -> Never:
    raise RuntimeError(message)


PageSize = Annotated[int, "1..100 constraint lives here"]

Why Annotated Matters

  • Static type checkers mostly care about the underlying type.
  • Frameworks such as FastAPI and Pydantic can also consume the attached metadata.
  • That makes Annotated a central meeting point between typing and runtime behavior.

When Aliases Help

Domain meaning appears

Names such as `UserId`, `OrderNumber`, or `Slug` make the API intent clearer than plain primitives.

Complex unions repeat

Long repeated type expressions often read much better once named.

Metadata needs reuse

`Annotated` aliases can package both type meaning and reusable metadata.

Avoid premature aliases

Wrapping every simple type in an alias can make code harder to read, not easier.

Official Sources

Built with VitePress for a Python 3.14 handbook.