Skip to main content
Brave Programmer Logo

BraveProgrammer

BraveProgrammer

HomeProjectsBlogsCoursesLessonsAbout

Site footer

BraveProgrammer

Free coding courses, practical tutorials, and real projects from BraveProgrammer. Learn web development with React, Next.js, and TypeScript.

Navigation

  • Home
  • Projects
  • Blogs
  • Courses

Resources

  • About
  • Lessons

© 2026 BraveProgrammer. All rights reserved.

  1. Courses
  2. /
  3. Python Fundamentals

Lesson 53 of 55 · Python

Type Hinting & Static Typing

Duration: 20 minutes

Type Hinting & Static Typing

Python’s dynamic nature makes it easy to write quick scripts, but large code‑bases benefit from type annotations – they improve readability, help IDEs, and enable static analysis tools like mypy.

1️⃣ Basic Syntax (PEP 484)

def greet(name: str) -> str:
    return f"Hello, {name}!"

age: int = 27
items: list[int] = [1, 2, 3]
  • The part after : is the type hint for a variable.
  • The part after -> is the return type.

2️⃣ The typing Module

from typing import List, Tuple, Dict, Optional, Union, Any, Callable

def process(data: List[int]) -> Tuple[int, float]:
    total = sum(data)
    avg = total / len(data) if data else 0.0
    return total, avg

Frequently used types

HintMeaning
List[int]List containing only integers
Dict[str, Any]Mapping from strings to any value
Optional[str]str or None
Union[int, float]Either int or float
Callable[[int, int], int]Function taking two ints and returning an int

3️⃣ Runtime vs. Static Checking

  • Runtime: Python ignores hints – they are just metadata.
  • Static: Tools like mypy, pyright or IDEs read hints and warn about mismatches.
# Install mypy
pip install mypy

# Run a type‑check on a file
mypy myscript.py

Typical output:

myscript.py:5: error: Incompatible types in assignment (expression has type "int", variable has type "str")

4️⃣ Gradual Adoption

  1. Add hints to public APIs first (functions, classes).
  2. Run mypy --strict locally; fix the most critical errors.
  3. Keep the code working – you can always add more hints later.

5️⃣ Advanced Topics (quick glance)

  • TypedDict – typed dictionaries for JSON‑like data.
  • Protocol – structural subtyping (duck‑typing with static checks).
  • New‑type – create distinct types from existing ones (e.g., UserId = NewType('UserId', int)).
  • Annotated – attach extra metadata (e.g., for validation libraries).

When you combine type hints with good test coverage, your Python projects become far easier to maintain and refactor.

Previous: Version Control with GitNext: Testing with pytest