Proposal: Adding Intersection Types (&
) to Python Type Hints
#1906
Labels
topic: feature
Discussions about new features for Python's type annotations
Introduction
Python's type hinting system, introduced in PEP 484 and expanded in subsequent PEPs, has become a powerful tool for static type checking and improving code readability. However, one feature that is currently missing is intersection types, which allow specifying that a value must satisfy multiple types or protocols simultaneously. This feature is particularly useful for expressing complex constraints, such as requiring an object to implement multiple interfaces (similar to Rust's trait bounds).
This proposal suggests adding support for the
&
operator in Python's type hints to represent intersection types.Motivation
Expressing Multiple Constraints:
Speak
andWalk
protocols, there is no straightforward way to express this in type hints.Union[Type1, Type2]
orType1
with runtime checks are either incorrect or cumbersome.Alignment with Other Languages:
Improved Static Analysis:
mypy
,pyright
) to perform more precise type inference and validation, reducing the likelihood of runtime errors.Better Code Documentation:
Proposed Syntax
The
&
operator would be used to denote intersection types in type hints. For example:Here,
Speak & Walk
indicates that theanimal
parameter must satisfy both theSpeak
andWalk
protocols.Semantics
Compatibility:
A & B
if it satisfies bothA
andB
. For example:Static Type Checking:
Runtime Behavior:
Backward Compatibility
&
operator for intersection types would be fully backward compatible. Existing code that does not use this feature would remain unaffected.The text was updated successfully, but these errors were encountered: