Sobes.tech
Junior

When are type annotations used in Python?

sobes.tech AI

Answer from AI

Type hints in Python are used for:

  • Improving code readability: Indicate expected data types for function arguments, return values, and variables.
  • Static code analysis: Tools like MyPy, Pyright use annotations to check types during development, catching potential errors before runtime.
  • IDE support: Modern IDEs use annotations for autocompletion, hints, and refactoring.
  • Self-documenting: Annotations act as documentation, describing interfaces.
  • Increased reliability: Static analysis reduces runtime type errors.
  • Runtime type hints: Although annotations do not affect runtime by default, they can be used with libraries for runtime type checking.

Example:

# Variable with int type
age: int = 30

# Function with argument and return type annotations
def add(a: int, b: int) -> int:
    return a + b

# Using typing module types
from typing import List, Dict, Optional

# List of strings
names: List[str] = ["Alice", "Bob"]

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

# Optional value (can be None or int)
optional_number: Optional[int] = None

Main annotation types:

  • Built-in types (int, str, float, bool, list, dict, tuple, set, etc.)
  • Types from typing module (List, Dict, Tuple, Set, Union, Optional, Any, Callable, etc.)
  • User-defined classes

Note that type annotations do not impose restrictions at runtime. Python remains dynamically typed. Annotations are mainly used for static analysis and documentation.