DevFox Labs
HomeCoursesRoadmapsChallengesToolsAboutContact
intermediate30 minby DevFoxUpdated on 1 Aug 2026

Type Hints That Earn Their Keep

Annotations a checker can actually use, gradual typing in an untyped codebase, Optional and unions done properly, and the hints that add noise without adding safety.

  • Python
  • Types
Type Hints That Earn Their Keep. Read this lesson at .

Previous lesson · 2 of 20Packaging Your ProjectNext lesson · 4 of 20Dataclasses and Modelling Data

On this page

  • Annotations, and what they do not do
  • Running a checker
  • The notation you need
  • Accept broadly, return precisely
  • Any, and why it spreads
  • Describing behaviour, not classes
  • Where hints pay, and where they do not
  • A cheat sheet to keep
  • Where to go next
DevFox Labs

Structured lessons and courses for developers who care about craft.

Platform

HomeCoursesRoadmapsAll lessonsChallengesAboutContactRSS feed

Legal

Terms of ServicePrivacy PolicyCookie Policy

© 2026 DevFox Labs. All rights reserved.

    You are reading a function someone wrote eight months ago:

    python
    def process(items, config, retries):
        ...

    What is items — a list of paths, a list of photo objects, a dictionary? Is config your config class or a plain dict? The only way to find out is to read the body, and then read the bodies of everything it calls. The information existed in somebody's head and was never written down.

    Type hints write it down, in a form a tool can check. By the end of this lesson you will annotate code usefully, run a checker over it, and know which hints are worth the characters and which are noise — because a codebase that annotates everything indiscriminately is barely better than one that annotates nothing.

    Annotations, and what they do not do

    python
    def make_caption(filename: str, separator: str = "_") -> str:
        words = filename.replace(separator, " ")
        return words.title()

    filename: str says this parameter is a string. -> str says the function returns one. Variables can be annotated too, though you rarely need to:

    python
    count: int = 0
    names: list[str] = []

    Now the crucial fact: Python ignores all of this at runtime.

    python
    make_caption(42)      # runs, and fails inside with AttributeError

    Nothing checks the hint as the program runs. Annotations are documentation that a separate tool can verify — which is a different and better thing than a runtime check, because it finds the problem before the code ever runs, across every path, including the ones your tests missed.

    Running a checker

    Hints do nothing on their own. The value arrives with a type checker:

    bash
    python -m pip install mypy
    mypy src/
    text
    src/photo_tools/captions.py:14: error: Argument 1 to
    "make_caption" has incompatible type "int"; expected "str"

    The alternatives are pyright (fast, what most editors use) and ty. Any of them; the point is that one runs, in CI, on every change. Hints nobody checks drift out of date and become confidently wrong documentation, which is worse than none.

    Start permissive and tighten:

    toml
    [tool.mypy]
    python_version = "3.11"
    warn_return_any = true
    warn_unused_ignores = true
    
    # turn this on per-module as you annotate
    disallow_untyped_defs = false

    Adopt it module by module

    Do not annotate a large codebase in one pass. Turn the checker on with lenient settings so it passes immediately, then enable disallow_untyped_defs for one module at a time, starting with the ones with the most callers. A checker that is green today and gets stricter each week gets adopted; one that reports four thousand errors on day one gets switched off.

    The notation you need

    Containers say what is inside them:

    | means "either":

    That return type is the most useful annotation in Python. It says out loud that this function sometimes finds nothing — which is exactly the fact that produces AttributeError: 'NoneType' object has no attribute 'name' when it is not written down. A checker will now refuse to let you use the result without handling the None case.

    For a value that may be absent:

    Anything that can be looped over, without caring what it is:

    Iterable accepts a list, a tuple, a set, a generator. Writing list[int] there would reject three of those for no reason.

    And functions, since they are values too:

    Read Callable[[Photo], Photo] as "takes a Photo, returns a Photo".

    Accept broadly, return precisely

    The rule that decides most annotation questions.

    Bad — narrow input, vague output.

    Good — broad input, exact output.

    The parameter

    Broad. Iterable, not list.

    list[Photo] rejects a generator, a tuple and a set even though the body handles all three — so a caller with a generator has to build a list purely to satisfy an annotation.

    The return type

    Exact. int, never Any.

    Any here switches the checker off for every caller: whatever they do with that number, no error is possible.

    One vague return type disables checking well beyond the function it is on.

    Take the most general type your body works with; return the most specific type you produce

    Any, and why it spreads

    Any means "stop checking". It is sometimes correct — genuinely dynamic data, a boundary with an untyped library — and it is contagious in a way people underestimate:

    Everything derived from an Any is Any. One vague return type disables checking across a whole call chain.

    The alternative at boundaries is to say what you expect and verify it once:

    Now config.timeuot is an error at the point you wrote it.

    Describing behaviour, not classes

    Sometimes what you need is not a specific type but a capability:

    A Protocol says "anything with these methods". Nothing has to inherit from it or know it exists — your own classes, third-party classes and built-ins all satisfy it by shape. That matches how Python actually works, where code cares what a value can do rather than what it is.

    Two more you will meet:

    -> None is worth writing. It distinguishes a function that does something from one that forgot to say what it gives back.

    Where hints pay, and where they do not

    Annotate:

    • Every public function and method. These are the ones with callers who cannot see the body.
    • Anything returning X | None. This is the highest-value annotation there is.
    • Module-level constants whose type is not obvious from the value.
    • Empty containers, since results = [] tells a checker nothing.

    Do not bother with:

    • Obvious local variables. count: int = 0 says nothing the 0 did not.
    • Short private helpers whose whole body is visible in one screen.
    • Test functions, which take no arguments and return nothing.

    The measure is whether the annotation tells a reader or a checker something it did not already know. photo: Photo = Photo() is noise; cache: dict[str, list[Photo]] = {} is genuinely informative.

    Hints are not validation

    Nothing stops a caller passing the wrong type at runtime — data from a file, an API or a form arrives untyped and an annotation will not check it. Annotations are for code you control, checked before it runs. For data crossing into your program, you need actual validation, which is the next lesson's subject.

    A cheat sheet to keep

    Where to go next

    Your functions can now state what they expect and produce, a tool can prove those statements consistent, and you know which annotations earn their place. The single highest-value habit from this lesson is annotating X | None returns — it turns the most common runtime error in Python into a checker message.

    Next is Dataclasses and Modelling Data, which builds directly on this. Once you are describing types, the natural next question is how to describe your own — and the answer is usually not a hand-written class with five assignments in __init__.

    Before you move on, add hints to one module you already have and run a checker over it. Pay attention to the first three errors: in most codebases, at least one is a genuine bug rather than a missing annotation, and usually it is a function that can return None and a caller that never considered it.

    text
    BASICS
      def f(x: str, n: int = 0) -> str:
      count: int = 0
      ignored at runtime - a checker verifies them, not Python
    
    CONTAINERS
      list[str]   dict[str, int]   set[str]
      tuple[int, int]        exactly two
      tuple[str, ...]        any number
    
    EITHER, AND MAYBE-NOTHING
      Photo | None           <- the highest-value hint there is
      int | str
      width: int | None = None
    
    ABSTRACT - from collections.abc
      Iterable[int]          anything you can loop over  <- for parameters
      Sequence[int]          indexable and has a length
      Callable[[Photo], Photo]   takes a Photo, returns a Photo
    
    TYPING MODULE
      Any                    stops checking - contagious, avoid
      Protocol               "anything with these methods"
      TypedDict              a dict with known keys
      Self                   returns my own type
      -> None                does something, returns nothing
    
    THE RULE
      accept the broadest type the body handles
      return the most specific type you produce
    
    WORTH ANNOTATING
      public functions, anything returning X | None,
      empty containers, non-obvious constants
    
    NOT WORTH IT
      obvious locals, tiny private helpers, test functions
    
    RUNNING IT
      mypy src/     or pyright
      in CI, on every change
      start lenient, tighten per module
      hints nobody checks become confidently wrong
    python
    names: list[str]
    sizes: dict[str, int]              # keys are str, values are int
    point: tuple[int, int]             # exactly two ints
    row: tuple[str, ...]               # any number of strs
    tags: set[str]
    python
    def find(name: str) -> Photo | None:
        ...
    python
    def resize(photo: Photo, width: int | None = None) -> Photo:
        ...
    python
    from collections.abc import Iterable, Sequence, Callable
    
    def total(sizes: Iterable[int]) -> int:
        return sum(sizes)
    python
    def apply(photos: list[Photo],
              transform: Callable[[Photo], Photo]) -> list[Photo]:
        return [transform(p) for p in photos]
    python
    def total_size(photos: list[Photo]) -> Any:
        return sum(p.size for p in photos)
    python
    def total_size(photos: Iterable[Photo]) -> int:
        return sum(p.size for p in photos)
    python
    def load_config(path: str) -> Any:      # returns parsed JSON
        ...
    
    config = load_config("config.json")
    timeout = config.timeuot                # no error. Typo ships.
    python
    from typing import TypedDict
    
    class Config(TypedDict):
        output_folder: str
        limit: int
    
    def load_config(path: str) -> Config:
        ...
    python
    from typing import Protocol
    
    class Sized(Protocol):
        def __len__(self) -> int: ...
    
    def describe(thing: Sized) -> str:
        return f"{len(thing)} items"
    python
    from typing import Self
    
    class Photo:
        def resized(self, width: int) -> Self:      # returns my own type
            ...
    python
    def process(paths: list[str]) -> None:          # returns nothing
        ...