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
17 changes: 9 additions & 8 deletions pyflakes/checker.py
Original file line number Diff line number Diff line change
Expand Up @@ -690,7 +690,6 @@ class AnnotationState:
NONE = 0
STRING = 1
BARE = 2
STR_AS_TYPE = 3


def in_annotation(func):
Expand Down Expand Up @@ -745,8 +744,10 @@ def __init__(self, tree, filename='(none)', builtins=None,
self.root = tree

self.scopeStack = []
scope_tp = Checker._ast_node_scope[type(tree)]

self._running_deferred = False

scope_tp = Checker._ast_node_scope[type(tree)]
with self.in_scope(scope_tp):
for builtin in self.builtIns:
self.addBinding(None, Builtin(builtin))
Expand All @@ -767,6 +768,8 @@ def deferFunction(self, callable):
self._deferred.append((callable, self.scopeStack[:], self.offset))

def _run_deferred(self):
self._running_deferred = True

orig = (self.scopeStack, self.offset)

while self._deferred:
Expand Down Expand Up @@ -1055,10 +1058,8 @@ def handleNodeLoad(self, node, parent):
elif (
isinstance(binding, Importation) and
binding.is_lazy and
func_depth == 0 and (
self._in_annotation == AnnotationState.NONE or
self._in_annotation == AnnotationState.STR_AS_TYPE
)
func_depth == 0 and
not self._running_deferred
): # pragma: >=3.15 cover
self.report(messages.EagerUseOfLazyImport, node, name, binding.source)

Expand Down Expand Up @@ -1494,7 +1495,7 @@ def CALL(self, node):
self._handle_string_dot_format(node)

def _annotation(n: ast.AST) -> None:
with self._enter_annotation(AnnotationState.STR_AS_TYPE):
with self._enter_annotation(AnnotationState.BARE):
self.handleNode(n, node)

def _annotations(nodes: list[ast.AST]) -> None:
Expand Down Expand Up @@ -2070,7 +2071,7 @@ def ANNASSIGN(self, node):
if node.value:
# If the annotation is `TypeAlias`, handle the *value* as an annotation.
if _is_typing(node.annotation, 'TypeAlias', self.scopeStack):
with self._enter_annotation(AnnotationState.STR_AS_TYPE):
with self._enter_annotation(AnnotationState.BARE):
self.handleNode(node.value, node)
else:
self.handleNode(node.value, node)
Expand Down
12 changes: 11 additions & 1 deletion pyflakes/test/test_lazy_imports.py
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,9 @@ class C:
{y for _ in [...]} # evaluated comprehensions
{0: y for _ in [...]} # evaluated comprehensions

''', *([m.EagerUseOfLazyImport] * 8))
@y
def u(): pass
''', *([m.EagerUseOfLazyImport] * 9))

def test_lazy_imports_eager_use_in_type_alias(self):
self.flakes('''
Expand All @@ -102,3 +104,11 @@ def test_literal_in_type_statements_is_deferred(self):

type A = Literal[int]
''')

def test_literal_annotated_not_considered_eager(self):
self.flakes('''
lazy from x import y
from typing import Literal, Annotated
x: Literal[y]
z: Annotated[int, y]
''')
Loading