Skip to main content

One post tagged with "Python"

View All Tags

Examining the Problem of Forward References in Python Type Annotations

· 4 min read

Type Hints

Python 3 introduced a new syntax for adding type hints to variables and functions:

class Container:
def __init__(self, name: str):
"""Initializes an empty container with the specified name"""
self.name: str = name
self.items: list[str] = []

Python is not a strongly typed language, so type hints are not checked at runtime and mismatches do not cause an error. Rather, the annotations are intended to be processed by third-party static analyzers like [Mypy][mypy], to detect bugs as part of the CI process. Type hints also serve as an indicator of a library developer's intent and can be used to generate richer API documentation.

Forward References

One limitation of the annotation syntax is the ability to handle forward references.

class Container:
def transfer(self, other: 'Container') -> None:
"""Moves the contents of this container to the other container"""
other.items.extend(self.items)
self.items = []