Sobes.tech
Junior
221

What are annotations used for in Python?

Answer from AI

sobes.tech AI

Annotations are used to improve code readability, static analysis (linting), and type support for more reliable and predictable program behavior.

Main purposes of annotations:

  • Readability: Explicitly specify expected types of function arguments, return values, and variables, making the code clearer.
  • Static analysis: Tools like mypy can use annotations to check types without executing the code, identifying potential errors before runtime.
  • Documentation: Annotations serve as a form of documentation describing the interface of functions and class methods.
  • IDE support: Integrated development environments (IDEs) use annotations for autocomplete, syntax highlighting, and refactoring.

Examples of usage:

# Argument annotation and return type annotation
def add(a: int, b: int) -> int:
    return a + b

# Variable annotation
name: str = "Alice"

# List of strings annotation
ages: list[int] = [25, 30, 35]

# Dictionary annotation with str keys and int values
scores: dict[str, int] = {"math": 90, "science": 85}

It is important to note that type annotations in Python do not affect code execution by default. They are not strict type checks at runtime. However, additional libraries like pydantic can be used for runtime data validation based on annotations.