Skip to content
Python

Type Hints

Improve code readability with type annotations.

By EZ4Code Team
typingtype

Code

from typing import List, Dict, Optional, Union, Callable

def greet(name: str, times: int = 1) -> str:
    return f"Hello {name} " * times

def process(items: List[int]) -> Dict[str, int]:
    return {"sum": sum(items), "count": len(items)}

def find(value: int, items: list[int]) -> Optional[int]:
    return items.index(value) if value in items else None

Callback = Callable[[int, int], int]

# Python 3.10+ uses | for union types
def parse(x: int | str) -> int | None:
    return int(x) if x else None

Explanation

Type annotations are not enforced at runtime, but aid IDE hints and static checks.

More Python Snippets