Chapter 59
59 / 71

Type Hints

⏱️ 30 min

What might confuse you right now

"Python is dynamically typed. Are type hints even necessary?"

For small personal scripts, not really. But in team projects and long-term codebases, typing noticeably reduces silly bugs.

One-line definition

Type hints are explicit declarations of parameter, return, and variable types -- for IDEs and static analysis tools.

Real-life analogy

Adding types to code is like labeling storage bins. The next person who picks it up gets oriented way faster.

Minimal runnable example

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

Quick quiz (5 min)

  1. Add parameter/return types to 3 functions.
  2. Add generics to list and dict.
  3. Use Optional for nullable fields.

Quiz answer guidelines & grading criteria

  • Answer direction: working code that covers core conditions and edge inputs from the prompt.
  • Criterion 1 (Correctness): Main flow produces correct results, key branches execute.
  • Criterion 2 (Readability): Clear variable names, no excessive nesting.
  • Criterion 3 (Robustness): Basic protection against null values, type errors, or unexpected input.

Transfer task (homework)

Pick some old code, add complete type hints, and run mypy once.

Acceptance criteria

You can independently:

  • Write basic type annotations
  • Use Optional and container generics
  • Use static analysis to catch type issues

Common errors & debugging steps (beginner edition)

  • Can't understand the error: read the last line for the error type (e.g., TypeError, NameError), then trace back to the relevant code line.
  • Not sure about a variable's value: temporarily add print(variable, type(variable)) at key points to verify data matches expectations.
  • Code changes aren't taking effect: confirm the file is saved, you're running the right file, and your terminal environment (venv) is correct.

Common misconceptions

  • Misconception: Type hints automatically block errors at runtime.
  • Reality: Type hints are primarily for static analysis and readability. Python doesn't enforce them at runtime.