fix old-division check for int(...) (#2892)

This commit is contained in:
Anthony Sottile 2019-04-30 02:08:25 -07:00 committed by Claudiu Popa
parent 2bf5c61a3f
commit c26bd45edb
3 changed files with 31 additions and 13 deletions

View File

@ -5,7 +5,6 @@ repos:
- id: black
args: [--safe, --quiet]
exclude: functional|input|test/extension|test/regrtest_data|test/data
python_version: python3.6
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v2.1.0
hooks:

View File

@ -1069,14 +1069,18 @@ class Python3Checker(checkers.BaseChecker):
if not self._future_division and node.op == "/":
for arg in (node.left, node.right):
inferred = utils.safe_infer(arg)
# If we can infer the object and that object is not a numeric one, bail out.
# If we can infer the object and that object is not an int, bail out.
if inferred and not (
isinstance(inferred, astroid.Const)
and isinstance(inferred.value, (int, float))
(
isinstance(inferred, astroid.Const)
and isinstance(inferred.value, int)
)
or (
isinstance(inferred, astroid.Instance)
and inferred.name == "int"
)
):
break
if isinstance(arg, astroid.Const) and isinstance(arg.value, float):
break
else:
self.add_message("old-division", node=node)

View File

@ -456,10 +456,19 @@ class TestPython3Checker(testutils.CheckerTestCase):
self.checker.visit_importfrom(node)
def test_division(self):
node = astroid.extract_node("3 / 2 #@")
message = testutils.Message("old-division", node=node)
with self.assertAddsMessages(message):
self.checker.visit_binop(node)
nodes = astroid.extract_node(
"""\
from _unknown import a, b
3 / 2 #@
3 / int(a) #@
int(a) / 3 #@
a / b #@
"""
)
for node in nodes:
message = testutils.Message("old-division", node=node)
with self.assertAddsMessages(message):
self.checker.visit_binop(node)
def test_division_with_future_statement(self):
module = astroid.parse("from __future__ import division; 3 / 2")
@ -472,10 +481,16 @@ class TestPython3Checker(testutils.CheckerTestCase):
self.checker.visit_binop(node)
def test_division_by_float(self):
left_node = astroid.extract_node("3.0 / 2 #@")
right_node = astroid.extract_node(" 3 / 2.0 #@")
nodes = astroid.extract_node(
"""\
3.0 / 2 #@
3 / 2.0 #@
3 / float(a) #@
float(a) / 3 #@
"""
)
with self.assertNoMessages():
for node in (left_node, right_node):
for node in nodes:
self.checker.visit_binop(node)
def test_division_different_types(self):