Generics — typing documentation
Generic functions¶. Type variables can be used to define generic functions. These are functions where the types of the arguments or return value have some ...
Generic functions¶. Type variables can be used to define generic functions. These are functions where the types of the arguments or return value have some ...
Static Typing with Python. Tutorials. Guides. Reference. Specification. Typing PEPs.Type Checkers. Development Environments. Linters and Formatters.
Generic functions Generic methods and generic self Automatic self types using typing.Self Variance of generic types Type variables with upper bounds Type variables with constraints Declaring decorators Generic protocols Generic type aliases Generic class internals Credits Protocols and structural subtyping Predefined protocols Simple user ...
For example, if s has type str, then "hello" + s has type str. This matches the pre-existing behavior of type checkers.username: str expect_literal_string(f"hello {username}") # NOT OK. The format-string is constructed from 'username', # which has type 'str'.
An unpacked form of tuple (using an unpack operator *) can be used within a tuple type argument list. For example, tuple[int, *tuple[str]] is equivalent to tuple[int, str]. Unpacking an unbounded tuple preserves the unbounded tuple as it is.
Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. The Python Software Foundation is a non-profit corporation.
Typing Best Practices ¶ Introduction ¶ Over time, some best practices have proven themselves as useful when working with type hints in Python. Not all practices are applicable in all situations and some practices come down to personal style and preference, but they are a good default set of recommendations to fall back to, unless there is a specific reason to deviate. These best practices ...
String annotations ¶ When a type hint cannot be evaluated at runtime, that definition may be expressed as a string literal, to be resolved later. The string literal should contain a syntactically valid Python expression (i.e., compile (lit, '', 'eval') should succeed) that is a valid annotation expression.
Type comments were originally introduced to support type annotations in Python 2 and variable annotations before Python 3.6. While most type checkers still support them, they are considered obsolete, and type checkers are not required to support them. For example, replace:: x = 3 # type: int def f(x, y): # type: (int, int) -> int