Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 31 additions & 0 deletions packages/pyright-internal/src/analyzer/typeEvaluator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2905,6 +2905,37 @@ export function createTypeEvaluator(
}
break;
}

case ParseNodeType.Tuple: {
// If this is a tuple expression with at least one item and no
// unpacked items, and all of the items have declared types,
// we can assume a declared type for the resulting tuple. This
// is needed to enable bidirectional type inference when assigning
// to an unpacked tuple.
if (
expression.d.items.length > 0 &&
!expression.d.items.some((item) => item.nodeType === ParseNodeType.Unpack)
) {
const itemTypes: Type[] = [];
expression.d.items.forEach((expr) => {
const itemType = getDeclaredTypeForExpression(expr, usage);
if (itemType) {
itemTypes.push(itemType);
}
});

if (itemTypes.length === expression.d.items.length) {
// If all items have a declared type, return a tuple of those types.
return makeTupleObject(
evaluatorInterface,
itemTypes.map((t) => {
return { type: t, isUnbounded: false };
})
);
}
}
break;
}
}

if (symbol) {
Expand Down
33 changes: 33 additions & 0 deletions packages/pyright-internal/src/tests/samples/solver45.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
# This sample tests the case where an expression is assigned to an unpacked
# tuple, and the correctly-inferred type of the expression depends on
# bidirectional type inference.

from typing import Literal, TypedDict


def func1[S, T](v: S | T, s: type[S], t: type[T]) -> tuple[S | None, T | None]: ...


def test1():
a: int | None
b: str | None

a, b = func1(1, int, str)


class TD1(TypedDict):
a: int


def test2():
a: TD1
b: TD1

a, b = ({"a": 1}, {"a": 2})


def test3():
a: Literal[1]
b: Literal[2]

a, b = (1, 2)
6 changes: 6 additions & 0 deletions packages/pyright-internal/src/tests/typeEvaluator2.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -843,6 +843,12 @@ test('Solver44', () => {
TestUtils.validateResults(analysisResults, 0);
});

test('Solver45', () => {
const analysisResults = TestUtils.typeAnalyzeSampleFiles(['solver45.py']);

TestUtils.validateResults(analysisResults, 0);
});

test('SolverScoring1', () => {
const analysisResults = TestUtils.typeAnalyzeSampleFiles(['solverScoring1.py']);

Expand Down
Loading