Fix list concatenation under contextual list hint #2142
+88
−0
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Fixes #2141.
What
When a
list[T]contextual hint is available (assignment/return annotation) and both operands of+are fresh list-producing expressions (list literal or list comprehension), propagate the hint into both operands.This makes cases like:
l2: list[Base] = [A()] + [B()]def f() -> list[Base]: return [A()] + [B()]work without making
listcovariant globally.Why
List literals already use contextual typing via
decompose_list, but+previously inferred operands without passing the hint (except[X] * int). That caused[A()] + [B()]to be inferred aslist[A | B]and fail againstlist[Base]due to invariance.Tests
l2and ensuring no-contextreveal_type([A()] + [B()])remainslist[A | B].Notes
The hint is only propagated when both operands are fresh to avoid masking invariance errors for expressions involving non-fresh operands.