Python6 min read

Python Type Hints

Add type hints for better code clarity.

Michael Brown
December 18, 2025
0.0k0

Make code more readable.

Basic Type Hints

```python def greet(name: str) -> str: return f"Hello {name}!"

age: int = 25 price: float = 19.99 is_active: bool = True ```

Collection Type Hints

```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) ```

Optional Types

```python from typing import Optional

def find_user(user_id: int) -> Optional[str]: if user_id == 1: return "Tom" return None

result = find_user(1) # Returns str or None ```

Union Types

```python from typing import Union

def process(value: Union[int, str]) -> str: return str(value)

process(123) # OK process("abc") # OK ```

Function Type Hints

```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

result = apply(add, 5, 3) # 8 ```

Remember

- Type hints improve code readability - Not enforced at runtime - Use mypy for type checking

#Python#Intermediate#Type Hints