Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions pyflakes/checker.py
Original file line number Diff line number Diff line change
Expand Up @@ -2102,11 +2102,22 @@ def TUPLE(self, node):

LIST = TUPLE

def _in_try(self, node): # pragma: >=3.15 cover
while True:
node = self.getParent(node)
if isinstance(node, (ast.Try, ast.TryStar, ast.ExceptHandler)):
return True
elif isinstance(node, ast.Module):
return False

def IMPORT(self, node):
lazy = sys.version_info >= (3, 15) and node.is_lazy
if lazy and not isinstance(self.scope, ModuleScope): # pragma: >=3.15 cover
self.report(messages.LazyImportNotAtModuleScope, node)
return
elif lazy and self._in_try(node): # pragma: >=3.15 cover
self.report(messages.LazyImportNotAtModuleScope, node)
return

for alias in node.names:
if '.' in alias.name and not alias.asname:
Expand All @@ -2130,6 +2141,9 @@ def IMPORTFROM(self, node):
if lazy and not isinstance(self.scope, ModuleScope): # pragma: >=3.15 cover
self.report(messages.LazyImportNotAtModuleScope, node)
return
elif lazy and self._in_try(node): # pragma: >=3.15 cover
self.report(messages.LazyImportNotAtModuleScope, node)
return

module = ('.' * node.level) + (node.module or '')

Expand Down
27 changes: 27 additions & 0 deletions pyflakes/test/test_lazy_imports.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,33 @@ class C:
lazy from y import z
''', m.LazyImportNotAtModuleScope, m.LazyImportNotAtModuleScope)

def test_lazy_import_not_at_module_scope_try(self):
self.flakes('''
try: lazy import x
except AssertionError: lazy import x
else: lazy import x
finally: lazy import x

try: lazy import x
except* AssertionError: ...

try:
if True:
lazy import x
except AssertionError: ...

try: lazy from x import y
except AssertionError: ...
''', *(7 * [m.LazyImportNotAtModuleScope]))

self.flakes('''
# allowed
if True:
lazy import x

def f(): print(x)
''')

def test_lazy_imports_eager_use_ok(self):
self.flakes('''
lazy from x import y
Expand Down
Loading