Skip to content

Commit 22bcb10

Browse files
committed
do not fold is/isnot
1 parent de026a9 commit 22bcb10

File tree

1 file changed

+18
-19
lines changed

1 file changed

+18
-19
lines changed

Python/ast_opt.c

Lines changed: 18 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -650,26 +650,38 @@ fold_compare(expr_ty node, PyArena *arena, _PyASTOptimizeState *state)
650650
};
651651

652652
if (node->v.Compare.left->kind == Constant_kind) {
653+
653654
PyObject *lhs = node->v.Compare.left->v.Constant.value;
654-
expr_ty curr_expr;
655655

656656
for (int i=0; i < asdl_seq_LEN(args); i++) {
657-
curr_expr = (expr_ty)asdl_seq_GET(args, i);
657+
658+
expr_ty curr_expr = (expr_ty)asdl_seq_GET(args, i);
658659

659660
if (curr_expr->kind != Constant_kind) {
661+
/* try to fold only if every comparator is constant */
660662
goto exit;
661663
}
662664

663-
PyObject *rhs = curr_expr->v.Constant.value;
664665
int op = asdl_seq_GET(ops, i);
665-
int res;
666+
667+
if (op == Is || op == IsNot) {
668+
/*
669+
Do not fold expression for now if "is"/"is not" is present.
670+
It breaks expected syntax warnings. For example:
671+
>>> 1 is 1
672+
<python-input-0>:1: SyntaxWarning: "is" with 'int' literal. Did you mean "=="?
673+
*/
674+
goto exit;
675+
}
676+
677+
PyObject *rhs = curr_expr->v.Constant.value;
666678

667679
switch (op) {
668680
case Eq: case NotEq:
669681
case Gt: case Lt:
670682
case GtE: case LtE:
671683
{
672-
res = PyObject_RichCompareBool(lhs, rhs, richcompare_table[op]);
684+
int res = PyObject_RichCompareBool(lhs, rhs, richcompare_table[op]);
673685
if (res < 0) {
674686
/* error */
675687
if (PyErr_Occurred()) {
@@ -686,7 +698,7 @@ fold_compare(expr_ty node, PyArena *arena, _PyASTOptimizeState *state)
686698
case In:
687699
case NotIn:
688700
{
689-
res = PySequence_Contains(rhs, lhs);
701+
int res = PySequence_Contains(rhs, lhs);
690702
if (res < 0) {
691703
/* error */
692704
if (PyErr_Occurred()) {
@@ -703,19 +715,6 @@ fold_compare(expr_ty node, PyArena *arena, _PyASTOptimizeState *state)
703715
}
704716
break;
705717
}
706-
case Is:
707-
case IsNot:
708-
{
709-
res = Py_Is(lhs, rhs);
710-
if (op == IsNot) {
711-
res = !res;
712-
}
713-
if (!res) {
714-
/* shortcut, whole expression is False */
715-
return make_const(node, Py_False, arena);
716-
}
717-
break;
718-
}
719718
}
720719
lhs = rhs;
721720
}

0 commit comments

Comments
 (0)