Skip to content

Commit 3bcbedc

Browse files
bpo-34850: Emit a warning for "is" and "is not" with a literal. (GH-9642)
1 parent e55cf02 commit 3bcbedc

File tree

5 files changed

+95
-11
lines changed

5 files changed

+95
-11
lines changed

Doc/whatsnew/3.8.rst

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -442,6 +442,13 @@ Changes in Python behavior
442442
in the leftmost :keyword:`!for` clause).
443443
(Contributed by Serhiy Storchaka in :issue:`10544`.)
444444

445+
* The compiler now produces a :exc:`SyntaxWarning` when identity checks
446+
(``is`` and ``is not``) are used with certain types of literals
447+
(e.g. strings, ints). These can often work by accident in CPython,
448+
but are not guaranteed by the language spec. The warning advises users
449+
to use equality tests (``==`` and ``!=``) instead.
450+
(Contributed by Serhiy Storchaka in :issue:`34850`.)
451+
445452

446453
Changes in the Python API
447454
-------------------------

Lib/test/test_ast.py

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1146,11 +1146,12 @@ def test_stdlib_validates(self):
11461146
tests = [fn for fn in os.listdir(stdlib) if fn.endswith(".py")]
11471147
tests.extend(["test/test_grammar.py", "test/test_unpack_ex.py"])
11481148
for module in tests:
1149-
fn = os.path.join(stdlib, module)
1150-
with open(fn, "r", encoding="utf-8") as fp:
1151-
source = fp.read()
1152-
mod = ast.parse(source, fn)
1153-
compile(mod, fn, "exec")
1149+
with self.subTest(module):
1150+
fn = os.path.join(stdlib, module)
1151+
with open(fn, "r", encoding="utf-8") as fp:
1152+
source = fp.read()
1153+
mod = ast.parse(source, fn)
1154+
compile(mod, fn, "exec")
11541155

11551156

11561157
class ConstantTests(unittest.TestCase):

Lib/test/test_grammar.py

Lines changed: 30 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1226,11 +1226,33 @@ def test_comparison(self):
12261226
if 1 > 1: pass
12271227
if 1 <= 1: pass
12281228
if 1 >= 1: pass
1229-
if 1 is 1: pass
1230-
if 1 is not 1: pass
1229+
if x is x: pass
1230+
if x is not x: pass
12311231
if 1 in (): pass
12321232
if 1 not in (): pass
1233-
if 1 < 1 > 1 == 1 >= 1 <= 1 != 1 in 1 not in 1 is 1 is not 1: pass
1233+
if 1 < 1 > 1 == 1 >= 1 <= 1 != 1 in 1 not in x is x is not x: pass
1234+
1235+
def test_comparison_is_literal(self):
1236+
def check(test, msg='"is" with a literal'):
1237+
with self.assertWarnsRegex(SyntaxWarning, msg):
1238+
compile(test, '<testcase>', 'exec')
1239+
with warnings.catch_warnings():
1240+
warnings.filterwarnings('error', category=SyntaxWarning)
1241+
with self.assertRaisesRegex(SyntaxError, msg):
1242+
compile(test, '<testcase>', 'exec')
1243+
1244+
check('x is 1')
1245+
check('x is "thing"')
1246+
check('1 is x')
1247+
check('x is y is 1')
1248+
check('x is not 1', '"is not" with a literal')
1249+
1250+
with warnings.catch_warnings():
1251+
warnings.filterwarnings('error', category=SyntaxWarning)
1252+
compile('x is None', '<testcase>', 'exec')
1253+
compile('x is False', '<testcase>', 'exec')
1254+
compile('x is True', '<testcase>', 'exec')
1255+
compile('x is ...', '<testcase>', 'exec')
12341256

12351257
def test_binary_mask_ops(self):
12361258
x = 1 & 1
@@ -1520,9 +1542,11 @@ def test_paren_evaluation(self):
15201542
self.assertEqual(16 // (4 // 2), 8)
15211543
self.assertEqual((16 // 4) // 2, 2)
15221544
self.assertEqual(16 // 4 // 2, 2)
1523-
self.assertTrue(False is (2 is 3))
1524-
self.assertFalse((False is 2) is 3)
1525-
self.assertFalse(False is 2 is 3)
1545+
x = 2
1546+
y = 3
1547+
self.assertTrue(False is (x is y))
1548+
self.assertFalse((False is x) is y)
1549+
self.assertFalse(False is x is y)
15261550

15271551
def test_matrix_mul(self):
15281552
# This is not intended to be a comprehensive test, rather just to be few
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
The compiler now produces a :exc:`SyntaxWarning` when identity checks
2+
(``is`` and ``is not``) are used with certain types of literals
3+
(e.g. strings, ints). These can often work by accident in CPython,
4+
but are not guaranteed by the language spec. The warning advises users
5+
to use equality tests (``==`` and ``!=``) instead.

Python/compile.c

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2284,6 +2284,47 @@ compiler_class(struct compiler *c, stmt_ty s)
22842284
return 1;
22852285
}
22862286

2287+
/* Return 0 if the expression is a constant value except named singletons.
2288+
Return 1 otherwise. */
2289+
static int
2290+
check_is_arg(expr_ty e)
2291+
{
2292+
if (e->kind != Constant_kind) {
2293+
return 1;
2294+
}
2295+
PyObject *value = e->v.Constant.value;
2296+
return (value == Py_None
2297+
|| value == Py_False
2298+
|| value == Py_True
2299+
|| value == Py_Ellipsis);
2300+
}
2301+
2302+
/* Check operands of identity chacks ("is" and "is not").
2303+
Emit a warning if any operand is a constant except named singletons.
2304+
Return 0 on error.
2305+
*/
2306+
static int
2307+
check_compare(struct compiler *c, expr_ty e)
2308+
{
2309+
Py_ssize_t i, n;
2310+
int left = check_is_arg(e->v.Compare.left);
2311+
n = asdl_seq_LEN(e->v.Compare.ops);
2312+
for (i = 0; i < n; i++) {
2313+
cmpop_ty op = (cmpop_ty)asdl_seq_GET(e->v.Compare.ops, i);
2314+
int right = check_is_arg((expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
2315+
if (op == Is || op == IsNot) {
2316+
if (!right || !left) {
2317+
const char *msg = (op == Is)
2318+
? "\"is\" with a literal. Did you mean \"==\"?"
2319+
: "\"is not\" with a literal. Did you mean \"!=\"?";
2320+
return compiler_warn(c, msg);
2321+
}
2322+
}
2323+
left = right;
2324+
}
2325+
return 1;
2326+
}
2327+
22872328
static int
22882329
cmpop(cmpop_ty op)
22892330
{
@@ -2363,6 +2404,9 @@ compiler_jump_if(struct compiler *c, expr_ty e, basicblock *next, int cond)
23632404
return 1;
23642405
}
23652406
case Compare_kind: {
2407+
if (!check_compare(c, e)) {
2408+
return 0;
2409+
}
23662410
Py_ssize_t i, n = asdl_seq_LEN(e->v.Compare.ops) - 1;
23672411
if (n > 0) {
23682412
basicblock *cleanup = compiler_new_block(c);
@@ -3670,6 +3714,9 @@ compiler_compare(struct compiler *c, expr_ty e)
36703714
{
36713715
Py_ssize_t i, n;
36723716

3717+
if (!check_compare(c, e)) {
3718+
return 0;
3719+
}
36733720
VISIT(c, expr, e->v.Compare.left);
36743721
assert(asdl_seq_LEN(e->v.Compare.ops) > 0);
36753722
n = asdl_seq_LEN(e->v.Compare.ops) - 1;

0 commit comments

Comments
 (0)