Skip to content

Commit 824a12d

Browse files
committed
Omit code guarded by 'if TYPE_CHECKING'
This commit finds a problem that has been observed in read code. Consider the following code: ``` from typing import TYPE_CHECKING ... if TYPE_CHECKING from a import A, B from b import C ... def f() -> "B": ... def f() # Oops! C is acutally used here. C() ``` This commit ignores all code that is guarded by TYPE_CHECKING in order to find mistakes like this. This constant is always False when mypy is not running anyway.
1 parent c72d6cf commit 824a12d

File tree

2 files changed

+15
-1
lines changed

2 files changed

+15
-1
lines changed

pyflakes/checker.py

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1833,7 +1833,13 @@ def DICT(self, node):
18331833
def IF(self, node):
18341834
if isinstance(node.test, ast.Tuple) and node.test.elts != []:
18351835
self.report(messages.IfTuple, node)
1836-
self.handleChildren(node)
1836+
omit = []
1837+
# We don't process the body of the if-statement if it is guarded by
1838+
# if TYPE_CHECKING. This variable is always false when the code is
1839+
# running.
1840+
if _is_typing(node.test, 'TYPE_CHECKING', self.scopeStack):
1841+
omit.append("body")
1842+
self.handleChildren(node, omit=omit)
18371843

18381844
IFEXP = IF
18391845

pyflakes/test/test_imports.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1031,6 +1031,14 @@ def test_futureImportStar(self):
10311031
from __future__ import *
10321032
''', m.FutureFeatureNotDefined)
10331033

1034+
def test_ignoresTypingImports(self):
1035+
"""Imports within 'if TYPE_CHECKING' are ignored."""
1036+
self.flakes('''
1037+
from typing import TYPE_CHECKING
1038+
if TYPE_CHECKING:
1039+
from a import b
1040+
b()
1041+
''', m.UndefinedName)
10341042

10351043
class TestSpecialAll(TestCase):
10361044
"""

0 commit comments

Comments
 (0)