diff --git a/pyflakes/checker.py b/pyflakes/checker.py index ae2caff6..dbfa1508 100644 --- a/pyflakes/checker.py +++ b/pyflakes/checker.py @@ -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: @@ -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 '') diff --git a/pyflakes/test/test_lazy_imports.py b/pyflakes/test/test_lazy_imports.py index 6788765c..9665103c 100644 --- a/pyflakes/test/test_lazy_imports.py +++ b/pyflakes/test/test_lazy_imports.py @@ -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