Lesson 53 of 55
PythonType Hinting & Static Typing
20 minutes
Course progress96%
What you'll learn
Keep these ideas in mind as you work through the lesson.
Lesson 53 of 55
Python20 minutes
Keep these ideas in mind as you work through the lesson.
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.
def greet(name: str) -> str:
return f"Hello, {name}!"
age: int = 27
items: list[int] = [1, 2, 3]
: is the type hint for a variable.-> is the return type.typing Modulefrom 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
| Hint | Meaning |
|---|---|
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 |
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")
mypy --strict locally; fix the most critical errors.UserId = NewType('UserId', int)).When you combine type hints with good test coverage, your Python projects become far easier to maintain and refactor.