ProgrammingBackend Developer

Explain the functionality and purpose of type hints in Python. How do they affect program execution and what pitfalls exist when using them?

Pass interviews with Hintsage AI assistant

Answer.

Type hints are a way to explicitly indicate the expected types of variables, function arguments, and return values. The syntax was introduced in Python 3.5 (PEP 484). Annotations are static – the interpreter ignores them at runtime; they are intended for code analysis tools (mypy, Pyright, IDE).

Type hints help:

  • Improve readability and self-documentation of the code.
  • Allow tools to analyze and catch type errors before execution.
  • Are used in autocompletion, refactoring, and documentation.

Example:

def add(x: int, y: int) -> int: return x + y def show(items: list[str]) -> None: print(', '.join(items))

Trick question.

Common question:

Can type hints somehow affect the performance or correctness of code execution?

Answer: No, type hints do not affect performance or the function of the program at runtime. They are merely metadata. However, they can be used by third-party tools or frameworks for type checking and validation (e.g., in FastAPI).

Examples of real errors due to ignorance of the nuances of the topic.


Story

In a project, large dynamic structures were annotated with types using list, dict without specifying the elements (for example: def f(x: list): ...). As a result, static analyzers could not detect type errors because it was unclear what was inside the annotation.


Story

Used from __future__ import annotations to support postponed evaluation in Python 3.7 but forgot about it in one part of the project. This led to forward references causing errors during static analysis and at runtime when using certain frameworks.


Story

In a large project, the return type was incorrectly specified: forgot to import Optional, resulting in an error from mypy and a number of undocumented issues in the IDE, which hindered autocomplete and error highlighting.