Skip to content

Commit 02f55ed

Browse files
committed
Python 3 only allows import * at module level
1 parent f048360 commit 02f55ed

File tree

4 files changed

+34
-0
lines changed

4 files changed

+34
-0
lines changed

pyflakes/checker.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -960,6 +960,11 @@ def IMPORTFROM(self, node):
960960

961961
for alias in node.names:
962962
if alias.name == '*':
963+
# Only Python 2, local import * is a SyntaxWarning
964+
if not PY2 and not isinstance(self.scope, ModuleScope):
965+
self.report(messages.ImportStarNotPermitted,
966+
node, node.module)
967+
continue
963968
self.scope.importStarred = True
964969
self.report(messages.ImportStarUsed, node, node.module)
965970
continue

pyflakes/messages.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,14 @@ def __init__(self, filename, loc, name, orig_loc):
4949
self.message_args = (name, orig_loc.lineno)
5050

5151

52+
class ImportStarNotPermitted(Message):
53+
message = "'from %s import *' only allowed at module level"
54+
55+
def __init__(self, filename, loc, modname):
56+
Message.__init__(self, filename, loc)
57+
self.message_args = (modname,)
58+
59+
5260
class ImportStarUsed(Message):
5361
message = "'from %s import *' used; unable to detect undefined names"
5462

pyflakes/test/test_imports.py

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -606,7 +606,27 @@ def c(self):
606606
''')
607607

608608
def test_importStar(self):
609+
"""Use of import * at module level is reported."""
609610
self.flakes('from fu import *', m.ImportStarUsed)
611+
self.flakes('''
612+
try:
613+
from fu import *
614+
except:
615+
pass
616+
''', m.ImportStarUsed)
617+
618+
@skipIf(version_info < (3,),
619+
'import * below module level is a warning on Python 2')
620+
def test_localImportStar(self):
621+
"""import * is only allowed at module level."""
622+
self.flakes('''
623+
def a():
624+
from fu import *
625+
''', m.ImportStarNotPermitted)
626+
self.flakes('''
627+
class a:
628+
from fu import *
629+
''', m.ImportStarNotPermitted)
610630

611631
def test_packageImport(self):
612632
"""

pyflakes/test/test_undefined_names.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -73,6 +73,7 @@ def test_globalImportStar(self):
7373
"""Can't find undefined names with import *."""
7474
self.flakes('from fu import *; bar', m.ImportStarUsed)
7575

76+
@skipIf(version_info >= (3,), 'obsolete syntax')
7677
def test_localImportStar(self):
7778
"""
7879
A local import * still allows undefined names to be found

0 commit comments

Comments
 (0)