Skip to content

Commit

Permalink
Imports used only in doctest are unused
Browse files Browse the repository at this point in the history
doctests should import additional modules
if they are otherwise unused.
  • Loading branch information
jayvdb committed Nov 15, 2015
1 parent d6de471 commit a8ccb1c
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 9 deletions.
12 changes: 7 additions & 5 deletions pyflakes/checker.py
Expand Up @@ -485,15 +485,17 @@ def handleNodeLoad(self, node):

# try enclosing function scopes and global scope
importStarred = self.scope.importStarred
below_doctest = isinstance(self.scope, DoctestScope)
for scope in reversed(scopes):
importStarred = importStarred or scope.importStarred
try:
scope[name].used = (self.scope, node)
except KeyError:
pass
else:
if name in scope:
if not below_doctest:
scope[name].used = (self.scope, node)
return

if isinstance(scope, DoctestScope):
below_doctest = True

# look in the built-ins
if importStarred or name in self.builtIns:
return
Expand Down
52 changes: 48 additions & 4 deletions pyflakes/test/test_doctests.py
Expand Up @@ -9,7 +9,7 @@
from pyflakes.test.test_other import Test as TestOther
from pyflakes.test.test_imports import Test as TestImports
from pyflakes.test.test_undefined_names import Test as TestUndefinedNames
from pyflakes.test.harness import TestCase, skip
from pyflakes.test.harness import TestCase


class _DoctestMixin(object):
Expand Down Expand Up @@ -183,6 +183,16 @@ def doctest_stuff():
'''
""", m.UndefinedName)

def test_importAfterDoctest(self):
self.flakes("""
def doctest_stuff():
'''
>>> foo
'''
import foo
""", m.UnusedImport)

def test_importBeforeDoctest(self):
self.flakes("""
import foo
Expand All @@ -191,9 +201,8 @@ def doctest_stuff():
'''
>>> foo
'''
""")
""", m.UnusedImport)

@skip("todo")
def test_importBeforeAndInDoctest(self):
self.flakes('''
import foo
Expand All @@ -205,7 +214,7 @@ def doctest_stuff():
"""
foo
''', m.RedefinedWhileUnused)
''')

def test_importInDoctestAndAfter(self):
self.flakes('''
Expand All @@ -219,6 +228,41 @@ def doctest_stuff():
foo()
''')

def test_importRedefinedByFor(self):
self.flakes('''
import fu
def doctest_stuff():
"""
>>> for fu in range(2):
... pass
"""
fu.bar()
''', m.ImportShadowedByLoopVar)

def test_importUnusedRedefinedByFor(self):
self.flakes('''
import fu
def doctest_stuff():
"""
>>> for fu in range(2):
... pass
"""
''', m.UnusedImport, m.ImportShadowedByLoopVar)

def test_redefinedInDoctest(self):
self.flakes('''
from __future__ import with_statement
import fu
def doctest_stuff():
"""
>>> with open('foo') as fu:
... pass
"""
''', m.UnusedImport, m.RedefinedWhileUnused)

def test_offsetInDoctests(self):
exc = self.flakes('''
Expand Down

0 comments on commit a8ccb1c

Please sign in to comment.