PY-83741 Support type narrowing based on containment check for list and set literals

GitOrigin-RevId: d82555c5acf0251c26a04b46ae6da63d90e3fabc
This commit is contained in:
Petr
2025-08-28 15:55:44 +00:00
committed by intellij-monorepo-bot
parent 537f7cf601
commit fd3e7fd3df
2 changed files with 14 additions and 2 deletions
@@ -131,9 +131,9 @@ public class PyTypeAssertionEvaluator extends PyRecursiveElementVisitor {
}
private void processIn(@NotNull PyExpression lhs, @NotNull PyExpression rhs) {
if (rhs instanceof PyTupleExpression tupleExpr) {
if (rhs instanceof PyTupleExpression || rhs instanceof PyListLiteralExpression || rhs instanceof PySetLiteralExpression) {
pushAssertion(lhs, myPositive, (TypeEvalContext context) -> {
PyExpression[] elements = tupleExpr.getElements();
PyExpression[] elements = ((PySequenceExpression)rhs).getElements();
List<PyType> types = new ArrayList<>(elements.length);
for (PyExpression element : elements) {
PyType type = PyLiteralType.isNone(element) ? PyBuiltinCache.getInstance(element).getNoneType() : getLiteralType(element, context);
@@ -737,6 +737,18 @@ public class Py3TypeTest extends PyTestCase {
if a in (1, 2, ""):
expr = a
""");
doTest("Literal[1, 2]",
"""
def f(a: int):
if a in {1, 2, ""}:
expr = a
""");
doTest("Literal[1, 2]",
"""
def f(a: int):
if a in [1, 2, ""]:
expr = a
""");
doTest("Literal[-10, \"a\"]",
"""
from enum import Enum