🏷️

How to Use Type Hints in Python

PythonIntermediate

Add type annotations to your code.

Code Example

Python
# Basic type hints
def greet(name: str) -> str:
    return f"Hello, {name}!"

print(greet("Alice"))

# Multiple types
def process(value: int | str) -> str:
    return str(value)

print(process(42))
print(process("hello"))

# Optional types
from typing import Optional

def find_user(id: int) -> Optional[str]:
    users = {1: "Alice", 2: "Bob"}
    return users.get(id)

print(f"\nUser 1: {find_user(1)}")
print(f"User 99: {find_user(99)}")

# List and dict types
from typing import List, Dict

def sum_numbers(numbers: List[int]) -> int:
    return sum(numbers)

print(f"\nSum: {sum_numbers([1, 2, 3, 4, 5])}")

# Complex types
def process_data(data: Dict[str, List[int]]) -> Dict[str, int]:
    return {key: sum(values) for key, values in data.items()}

scores = {"Alice": [85, 90, 88], "Bob": [92, 95, 91]}
print(f"Totals: {process_data(scores)}")

# Type hints don't enforce at runtime
def add(a: int, b: int) -> int:
    return a + b

print(f"\nStill works: {add('hello', ' world')}")

Explanation

Type hints improve code readability and IDE support. Use -> for return type, : for parameters. Import from typing for complex types.

Related Tutorials