From 5625e16dca685a280180cead645113f6b4dc2eea Mon Sep 17 00:00:00 2001 From: Alex Waygood Date: Wed, 28 Jun 2023 10:50:18 +0100 Subject: [PATCH] Fix some edge-case bugs around improper use of `isinstance()` (#405) These all stem from the fact that `True == 1` and `isinstance(False, int)` --- pyi.py | 9 +++++---- tests/sysversioninfo.pyi | 4 ++++ 2 files changed, 9 insertions(+), 4 deletions(-) diff --git a/pyi.py b/pyi.py index 5a4585f1..889eab4c 100644 --- a/pyi.py +++ b/pyi.py @@ -1433,7 +1433,7 @@ def _check_subscript_version_check(self, node: ast.Compare) -> None: slc = version_info.slice if isinstance(slc, ast.Constant): # anything other than the integer 0 doesn't make much sense - if isinstance(slc.value, int) and slc.value == 0: + if type(slc.value) is int and slc.value == 0: must_be_single = True else: self.error(node, Y003) @@ -1445,7 +1445,7 @@ def _check_subscript_version_check(self, node: ast.Compare) -> None: elif ( # allow only [:1] and [:2] isinstance(slc.upper, ast.Constant) - and isinstance(slc.upper.value, int) + and type(slc.upper.value) is int and slc.upper.value in {1, 2} ): can_have_strict_equals = slc.upper.value @@ -1471,8 +1471,9 @@ def _check_version_check( ) -> None: comparator = node.comparators[0] if must_be_single: - if not isinstance(comparator, ast.Constant) or not isinstance( - comparator.value, int + if ( + not isinstance(comparator, ast.Constant) + or type(comparator.value) is not int ): self.error(node, Y003) elif not isinstance(comparator, ast.Tuple): diff --git a/tests/sysversioninfo.pyi b/tests/sysversioninfo.pyi index d7d52cdd..9c448117 100644 --- a/tests/sysversioninfo.pyi +++ b/tests/sysversioninfo.pyi @@ -1,14 +1,18 @@ import sys if sys.version_info[0] == 2: ... +if sys.version_info[0] == True: ... # Y003 Unrecognized sys.version_info check # E712 comparison to True should be 'if cond is True:' or 'if cond:' if sys.version_info[0.0] == 2: ... # Y003 Unrecognized sys.version_info check +if sys.version_info[False] == 2: ... # Y003 Unrecognized sys.version_info check if sys.version_info[0j] == 2: ... # Y003 Unrecognized sys.version_info check if sys.version_info[0] == (2, 7): ... # Y003 Unrecognized sys.version_info check if sys.version_info[0] == '2': ... # Y003 Unrecognized sys.version_info check if sys.version_info[1:] >= (7, 11): ... # Y003 Unrecognized sys.version_info check if sys.version_info[::-1] < (11, 7): ... # Y003 Unrecognized sys.version_info check if sys.version_info[:3] >= (2, 7): ... # Y003 Unrecognized sys.version_info check +if sys.version_info[:True] >= (2, 7): ... # Y003 Unrecognized sys.version_info check if sys.version_info[:1] == (2,): ... +if sys.version_info[:1] == (True,): ... # Y003 Unrecognized sys.version_info check if sys.version_info[:1] == (2, 7): ... # Y005 Version comparison must be against a length-1 tuple if sys.version_info[:2] == (2, 7): ... if sys.version_info[:2] == (2,): ... # Y005 Version comparison must be against a length-2 tuple