Python24 min read
Python Type Hints
Learn type hints for readability, safer refactoring, and better editor support, including lists, dicts, Optional, Union, and Callable.
Michael Brown
August 3, 2025
11.0k508
Type hints let you describe what type of data a variable or function expects.
Important:
Python will still run without type hints. Type hints are mainly for:
- clearer code
- better autocomplete in editors
- catching mistakes early with tools (like mypy)
## Basic type hints
```python
def greet(name: str) -> str:
return f"Hello {name}!"
age: int = 25
price: float = 19.99
is_active: bool = True
print(greet("Tom"))
```
Expected output:
```
Hello Tom!
```
## Collection hints (modern style)
```python
from typing import List, Dict, Tuple
names: List[str] = ["Tom", "Sarah", "Mike"]
scores: Dict[str, int] = {"Tom": 90, "Sarah": 85}
point: Tuple[int, int] = (10, 20)
print(names)
print(scores)
print(point)
```
## Optional (value can be None)
```python
from typing import Optional
def find_user(user_id: int) -> Optional[str]:
if user_id == 1:
return "Tom"
return None
print(find_user(1))
print(find_user(99))
```
Expected output:
```
Tom
None
```
## Union (multiple allowed types)
```python
from typing import Union
def process(value: Union[int, str]) -> str:
return str(value)
print(process(123))
print(process("abc"))
```
Expected output:
```
123
abc
```
## Callable (function as a parameter)
```python
from typing import Callable
def apply(func: Callable[[int, int], int], x: int, y: int) -> int:
return func(x, y)
def add(a: int, b: int) -> int:
return a + b
print(apply(add, 5, 3))
```
Expected output:
```
8
```
## Graph: what type hints change
```mermaid
flowchart LR
A[Write code] --> B[Add type hints]
B --> C[Editor autocomplete improves]
B --> D[Static checks catch mistakes]
B --> E[Code becomes clearer]
```
Type hints do not replace tests, but they make refactoring safer and reduce simple mistakes.
In the next lesson, you will learn threading basics, including when to use threads and when not to.
#Python#Intermediate#Type Hints