Compatibility annotations
A codebase still supports older Python versions and uses the typing module’s generic collection syntax.
Python · Type Alias
typing.List[T] describes lists containing elements of type T and can be used in type aliases. It is deprecated in current Python documentation; use built-in list[T] for new code.
typing.List is the generic form of the built-in list, parameterized with an element type such as List[int]. In current Python, it is retained for compatibility but deprecated; new annotations should use list[int] instead. A type alias assigns that parameterized type to another name for static type checking.
typing.List[T]| Name | Type | Description |
|---|---|---|
T | type parameter | The single element type contained by the list. |
A parameterized type used for static annotations; it does not construct a list at runtime.
typing.List[T] parameterizes the built-in list concept with one element type.List[int].type statement.typing.List is deprecated; prefer the built-in generic list for new annotations.Sequence or Iterable when mutation is not required.from typing import List
UserIds = List[int]
ids: UserIds = [101, 202, 303]
print(ids)Defines a reusable alias for a list of integers and uses it in an annotation.
A codebase still supports older Python versions and uses the typing module’s generic collection syntax.
A domain-specific name makes a repeated list type easier to read.
A function’s result is specifically a list of one element type.
typing.List[int] mean?List[T] is the generic typing form of list, where T describes the element type. For example, List[int] annotates a list whose elements are integers.
Follow-up: What should modern Python code use instead? Use the built-in generic syntax list[int], because typing.List is deprecated.
A type alias gives another name to a type expression, such as UserIds = List[int]. Static type checkers treat the alias as equivalent to the original type.
Follow-up: How can an alias be made explicit? Annotate the assignment with TypeAlias, although current Python documentation recommends the type statement instead.
List be used for function arguments?List is useful for describing list return values, but parameter annotations often benefit from abstract collection types. Sequence or Iterable can express that callers need only those operations rather than a concrete mutable list.
Follow-up: When is list[T] preferable for a parameter? Use it when the API specifically requires a list, especially when list-specific mutation or behavior is part of the contract.
listSequenceIterableTypeAliasTypeAliasType