What are Python Type Hints?
While Python is a dynamically typed language (variables don't need a declared type), type hints were introduced in Python 3.5 (PEP 484) to allow developers to formally declare the expected types for function arguments, return values, and variables.
Wait! Python does not enforce these types at runtime. They are purely for documentation, IDE auto-completion, and static analysis tools like
mypy.python
Complex Type Hints: Use typing
For more advanced scenarios, use the built-in
typing module.python
Modern Type Hints (Python 3.10+)
You no longer need to import
List, Dict, or Union. You can use built-in types and the pipe operator |.python
Structural Typing: Protocol (Python 3.8+)
Sometimes you don't care what an object is, but how it behaves (Duck Typing). A Protocol is like an interface in Java — it defines a set of methods an object must have.
python
Summary
| Feature | Syntax | Purpose |
|---|---|---|
| Simple Hint | name: str | Basic type declaration |
| Return Hint | -> int | Function output type |
| Optional | `str | None` |
| Union | `int | float` |
| Generic | List[T] / list[T] | Type that depends on another type |
| Protocol | class P(Protocol): | Formal interface mapping |
| Best For | IDE support, Documentation, Large refactors | |
| Mypy | mypy project/ | The tool that checks types staticly |
| TypeAlias | Scores = list[int] | Give a type a new name |