Skip to content

Commit

Permalink
Omit code guarded by 'if TYPE_CHECKING'
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
PetterS committed Apr 15, 2020
1 parent c72d6cf commit 824a12d
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 1 deletion.
8 changes: 7 additions & 1 deletion pyflakes/checker.py
Original file line number Diff line number Diff line change
Expand Up @@ -1833,7 +1833,13 @@ def DICT(self, node):
def IF(self, node):
if isinstance(node.test, ast.Tuple) and node.test.elts != []:
self.report(messages.IfTuple, node)
self.handleChildren(node)
omit = []
# We don't process the body of the if-statement if it is guarded by
# if TYPE_CHECKING. This variable is always false when the code is
# running.
if _is_typing(node.test, 'TYPE_CHECKING', self.scopeStack):
omit.append("body")
self.handleChildren(node, omit=omit)

IFEXP = IF

Expand Down
8 changes: 8 additions & 0 deletions pyflakes/test/test_imports.py
Original file line number Diff line number Diff line change
Expand Up @@ -1031,6 +1031,14 @@ def test_futureImportStar(self):
from __future__ import *
''', m.FutureFeatureNotDefined)

def test_ignoresTypingImports(self):
"""Imports within 'if TYPE_CHECKING' are ignored."""
self.flakes('''
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from a import b
b()
''', m.UndefinedName)

class TestSpecialAll(TestCase):
"""
Expand Down

0 comments on commit 824a12d

Please sign in to comment.