Site Tools


import-typing

Table of Contents

import typing

import typing is a Python import that provides type hints for static type checking. Use type annotations to document function signatures and catch bugs with tools like mypy before runtime.

Example

# Python
# description: type hints for functions and variables
 
from typing import List, Dict, Optional, Union
 
def process_names(names: List[str]) -> int:
    """Process a list of names and return count."""
    return len(names)
 
def find_user(user_id: int) -> Optional[Dict[str, str]]:
    """Find user by ID, return None if not found."""
    users = {1: {"name": "Alice"}, 2: {"name": "Bob"}}
    return users.get(user_id)
 
def convert(value: Union[int, str]) -> str:
    """Accept int or str, return string."""
    return str(value)
 
# Type hints for variables (Python 3.6+)
age: int = 30
names: List[str] = ["Alice", "Bob"]

Common types

  • List[T]: list of type T
  • Dict[K, V]: dict with keys K, values V
  • Tuple[T, ...]: tuple of type T
  • Set[T]: set of type T
  • Optional[T]: T or None (same as Union[T, None])
  • Union[T1, T2]: T1 or T2
  • Callable[[A, B], R]: function taking A, B and returning R
import-typing.md · Last modified: by 127.0.0.1