Useful Data Tips

Type Hints in Python

⏱️ 29 sec read 🐍 Python

Type hints add optional static typing to Python. They improve code documentation, enable better IDE autocomplete, and catch bugs early with static type checkers like mypy.

Basic Type Hints

def greet(name: str) -> str:
    return f"Hello, {name}"

def add(a: int, b: int) -> int:
    return a + b

# Variable annotations
age: int = 30
name: str = "Alice"
scores: list = [95, 87, 92]

Collection Types

from typing import List, Dict, Set, Tuple

# List of integers
numbers: List[int] = [1, 2, 3, 4]

# Dictionary with string keys and int values
scores: Dict[str, int] = {'Alice': 95, 'Bob': 87}

# Set of strings
tags: Set[str] = {'python', 'data', 'tips'}

# Tuple with specific types
coordinates: Tuple[float, float] = (40.7128, -74.0060)

Optional and Union Types

from typing import Optional, Union

# Optional means value can be None
def find_user(user_id: int) -> Optional[str]:
    if user_id == 1:
        return "Alice"
    return None  # OK

# Union means multiple possible types
def process_id(id_value: Union[int, str]) -> str:
    return str(id_value)

process_id(123)      # OK
process_id("abc")    # OK

Function Type Hints

from typing import Callable, List

# Function that takes a function as argument
def apply_to_list(func: Callable[[int], int], numbers: List[int]) -> List[int]:
    return [func(x) for x in numbers]

def square(x: int) -> int:
    return x ** 2

result = apply_to_list(square, [1, 2, 3])  # [1, 4, 9]

Custom Types and Classes

from typing import List

class User:
    def __init__(self, name: str, age: int) -> None:
        self.name = name
        self.age = age

def get_adult_users(users: List[User]) -> List[User]:
    return [u for u in users if u.age >= 18]

users = [User("Alice", 30), User("Bob", 17)]
adults = get_adult_users(users)

Generic Types

from typing import TypeVar, List

T = TypeVar('T')

def first_element(items: List[T]) -> T:
    return items[0]

# Works with any type
numbers = first_element([1, 2, 3])      # Returns int
names = first_element(['a', 'b', 'c'])  # Returns str

Type Aliases

from typing import List, Dict

# Create readable aliases for complex types
UserId = int
UserName = str
UserData = Dict[UserId, UserName]

def get_users() -> UserData:
    return {1: "Alice", 2: "Bob"}

# Vector is a list of floats
Vector = List[float]

def dot_product(v1: Vector, v2: Vector) -> float:
    return sum(x * y for x, y in zip(v1, v2))

Checking Types with mypy

# Install mypy
# pip install mypy

# Create file: example.py
def add(a: int, b: int) -> int:
    return a + b

result = add(5, "10")  # Type error!

# Run type checker
# mypy example.py
# error: Argument 2 to "add" has incompatible type "str"; expected "int"

Benefits of Type Hints

Pro Tip: Type hints are optional and don't affect runtime. Start adding them to function signatures gradually. Use mypy to catch type errors in your codebase before they become bugs.

← Back to Python Tips