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
Foundation builder
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.Protocolfor structural (duck) typing.
Syntax reference
Visual flow / code:
python
from typing import Protocoldef greet(name: str, times: int = 1) -> list[str]:return [f"hi {name}"] * times# Optional + uniondef find(id: int) -> User | None: ...# Genericsdef 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 / 4Step 1
def f(x: int) -> str:
Apply this step while implementing type hints & mypy in real code.
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.
Hands-on exercise
Interview preparation — practice these questions:
- What is gradual typing?
- Protocol vs ABC?
- Does Python enforce hints at runtime?
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.