Skip to content

Commit e5e6ca7

Browse files
perrinjeromeDanielNoord
authored andcommitted
checkers.utils.is_sys_guard: understands six.PY2 or six.PY3
Fixes #3501
1 parent 27b1ae7 commit e5e6ca7

File tree

3 files changed

+27
-2
lines changed

3 files changed

+27
-2
lines changed

doc/whatsnew/fragments/3501.feature

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
Understand `six.PY2` and `six.PY3` for conditional imports.
2+
3+
Closes #3501

pylint/checkers/utils.py

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1831,7 +1831,11 @@ def is_sys_guard(node: nodes.If) -> bool:
18311831
and value.as_string() == "sys.version_info"
18321832
):
18331833
return True
1834-
1834+
elif isinstance(node.test, nodes.Attribute) and node.test.as_string() in {
1835+
"six.PY2",
1836+
"six.PY3",
1837+
}:
1838+
return True
18351839
return False
18361840

18371841

tests/checkers/unittest_utils.py

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -400,9 +400,19 @@ def test_if_sys_guard() -> None:
400400
401401
if sys.some_other_function > (3, 8): #@
402402
pass
403+
404+
import six
405+
if six.PY2: #@
406+
pass
407+
408+
if six.PY3: #@
409+
pass
410+
411+
if six.something_else: #@
412+
pass
403413
"""
404414
)
405-
assert isinstance(code, list) and len(code) == 3
415+
assert isinstance(code, list) and len(code) == 6
406416

407417
assert isinstance(code[0], nodes.If)
408418
assert utils.is_sys_guard(code[0]) is True
@@ -412,6 +422,14 @@ def test_if_sys_guard() -> None:
412422
assert isinstance(code[2], nodes.If)
413423
assert utils.is_sys_guard(code[2]) is False
414424

425+
assert isinstance(code[3], nodes.If)
426+
assert utils.is_sys_guard(code[3]) is True
427+
assert isinstance(code[4], nodes.If)
428+
assert utils.is_sys_guard(code[4]) is True
429+
430+
assert isinstance(code[5], nodes.If)
431+
assert utils.is_sys_guard(code[5]) is False
432+
415433

416434
def test_if_typing_guard() -> None:
417435
code = astroid.extract_node(

0 commit comments

Comments
 (0)