Python Tutorial 0/52 lessons ~6 min read Lesson 38

    Type Hints & mypy

    Python is dynamically typed but supports gradual typing via type hints (PEP 484).

    Course progress0%
    Focus
    8 guided sections
    Practice signal
    Examples included
    Career prep
    Interview Q&A included

    Introduction

    Python is dynamically typed but supports gradual typing via type hints (PEP 484). Tools like mypy and pyright check them statically.

    Understanding the topic

    Core concepts to understand:

    • def f(x: int) -> str:
    • list[int], dict[str, int] (3.9+).
    • Optional[X] = X | None.
    • Protocol for structural (duck) typing.

    Syntax reference

    Visual flow / code:

    python
    from typing import Protocol
    def greet(name: str, times: int = 1) -> list[str]:
    return [f"hi {name}"] * times
    # Optional + union
    def find(id: int) -> User | None: ...
    # Generics
    def first[T](xs: list[T]) -> T: return xs[0]
    # Protocol (structural typing)
    class Comparable(Protocol):
    def __lt__(self, other) -> bool: ...
    def smallest[T: Comparable](xs: list[T]) -> T:
    return min(xs)

    Execution workflow

    1Type Hints & mypy Workflow
    1 / 4

    def f(x

    int) -> str:

    Real-world use

    Modern Python codebases (FastAPI, Pydantic, Litestar) are entirely typed — type hints power runtime validation, IDE autocomplete, and docs.

    Best practices

    • Type all public functions.
    • Run mypy/pyright in CI.
    • Use Protocols over abstract base classes.

    Advanced interview questions

    Interview Prep

    Practice concise answers, then expand each card for the explanation.

    3 questions
    1IntermediateQuestionWhat is gradual typing?+

    Answer

    Gradual typing lets you add type annotations incrementally: annotated code is checked by a static tool like mypy or pyright, and unannotated code is treated as Any and not checked. You can adopt it module by module without rewriting a codebase. The checking happens outside the interpreter, and Any acts as an escape hatch between typed and untyped parts.

    Follow-up

    What is the difference between Any and object?
    2AdvancedQuestionProtocol vs ABC?+

    Answer

    An ABC uses nominal typing: a class must inherit from it, or be registered, to count as a subtype. A typing.Protocol uses structural typing: any class with the required methods and attributes matches, without inheriting. Protocols suit duck-typed interfaces and third-party classes, while ABCs can share implementation and enforce abstract methods at instantiation. Use @runtime_checkable for isinstance checks on protocols, which only check method presence.

    Follow-up

    Which would you choose for a plugin interface?
    3BeginnerQuestionDoes Python enforce hints at runtime?+

    Answer

    No. Annotations are stored in __annotations__ and ignored by the interpreter, so passing the wrong type does not raise by itself. Enforcement comes from static checkers such as mypy, or from libraries that read the annotations at runtime, such as Pydantic or typeguard. That is why FastAPI can validate inputs based on hints even though plain Python does not.

    Follow-up

    What does from __future__ import annotations change?

    Summary

    In summary: Gradual typing = best of both. mypy/pyright + CI = safety.

    Ready to mark this lesson complete?Track your journey across the entire course.