From 30ca0f06b9891e5bd3cb2ee9ac7c88d42d8d8675 Mon Sep 17 00:00:00 2001 From: Apoorv Darshan Date: Thu, 9 Jul 2026 19:26:44 +0530 Subject: [PATCH] E721: flag swapped type comparisons like `int == type(obj)` E721 only fired when a `type(...)` call was on the left-hand side of `==` / `!=` (e.g. `type(obj) == int`). The swapped form `int == type(obj)` was silently ignored even though it is the same type comparison. `comparison_type` only inspected `match.group(1)`, the argument of the right-hand `type(...)` call, and suppressed the warning whenever that argument was a plain identifier. Because the two regex alternatives capture opposite sides, this made the check asymmetric: `type(obj) == x` was reported but the mirror `x == type(obj)` was not. Remove the identifier-based suppression so both operand orders are treated identically, and drop the now-unused capture groups from COMPARE_TYPE_REGEX. Add regression fixtures for the swapped `==` and `!=` forms to testing/data/E72.py. Fixes #1187. --- pycodestyle.py | 9 ++++----- testing/data/E72.py | 6 ++++++ 2 files changed, 10 insertions(+), 5 deletions(-) diff --git a/pycodestyle.py b/pycodestyle.py index 868e79d5..e53e8b0d 100755 --- a/pycodestyle.py +++ b/pycodestyle.py @@ -121,8 +121,8 @@ COMPARE_NEGATIVE_REGEX = re.compile(r'\b(?%&^]+|:=)(\s*)') @@ -1498,12 +1498,11 @@ def comparison_type(logical_line, noqa): Okay: if isinstance(obj, int): Okay: if type(obj) is int: E721: if type(obj) == type(1): + E721: if type(obj) == int: + E721: if int == type(obj): """ match = COMPARE_TYPE_REGEX.search(logical_line) if match and not noqa: - inst = match.group(1) - if inst and inst.isidentifier() and inst not in SINGLETONS: - return # Allow comparison for types which are not obvious yield ( match.start(), "E721 do not compare types, for exact checks use `is` / `is not`, " diff --git a/testing/data/E72.py b/testing/data/E72.py index 5d1046cb..d74350e8 100644 --- a/testing/data/E72.py +++ b/testing/data/E72.py @@ -4,6 +4,12 @@ #: E721 if type(res) != type(""): pass +#: E721 +if int == type(res): + pass +#: E721 +if str != type(res): + pass #: Okay res.type("") == "" #: Okay