Type HintsAdvanced
1Question 1 of 1
pythonHow do Type Hints and Static Type Checking with Mypy work in modern Python?
Explanation & Concept
Python 3.5+ supports optional static type annotations (`int`, `str`, `List`, `Dict`, `Optional`). Python itself does not enforce types at runtime, but static analyzers like **Mypy** and IDEs detect type bugs before execution.
Code Example
python
from typing import Optional
def format_user(user_id: int, nickname: Optional[str] = None) -> str:
if nickname is not None:
return f"User #{user_id}: {nickname.upper()}"
return f"User #{user_id}"
# Mypy flag check:
# mypy script.py --strictHow It Works & Key Takeaways
Type annotations act as executable documentation and prevent common runtime `AttributeError` and `TypeError` bugs.
Mock Test · 1 Questions · Optional
Ready for Async IO?
Take a quick test to evaluate yourself, or move straight to the next module.
Advanced1 questions