Skip to content

Commit

Permalink
Fix used-before-assignment false positive for TYPE_CHECKING elif …
Browse files Browse the repository at this point in the history
…branch imports (#8441)


Co-authored-by: Pierre Sassoulas <pierre.sassoulas@gmail.com>
  • Loading branch information
zenlyj and Pierre-Sassoulas authored Mar 30, 2023
1 parent 9f2de91 commit 4f89e7d
Show file tree
Hide file tree
Showing 8 changed files with 145 additions and 164 deletions.
4 changes: 4 additions & 0 deletions doc/whatsnew/fragments/8437.bugfix
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
Fix a ``used-before-assignment`` false positive when imports
are made under the ``TYPE_CHECKING`` else if branch.

Closes #8437
47 changes: 0 additions & 47 deletions pylint/checkers/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -2120,53 +2120,6 @@ def is_class_attr(name: str, klass: nodes.ClassDef) -> bool:
return False


def is_defined(name: str, node: nodes.NodeNG) -> bool:
"""Searches for a tree node that defines the given variable name."""
is_defined_so_far = False

if isinstance(node, nodes.NamedExpr):
is_defined_so_far = node.target.name == name

if isinstance(node, (nodes.Import, nodes.ImportFrom)):
is_defined_so_far = any(node_name[0] == name for node_name in node.names)

if isinstance(node, nodes.With):
is_defined_so_far = any(
isinstance(item[1], nodes.AssignName) and item[1].name == name
for item in node.items
)

if isinstance(node, (nodes.ClassDef, nodes.FunctionDef)):
is_defined_so_far = node.name == name

if isinstance(node, nodes.AnnAssign):
is_defined_so_far = (
node.value
and isinstance(node.target, nodes.AssignName)
and node.target.name == name
)

if isinstance(node, nodes.Assign):
is_defined_so_far = any(
any(
(
(
isinstance(elt, nodes.Starred)
and isinstance(elt.value, nodes.AssignName)
and elt.value.name == name
)
or (isinstance(elt, nodes.AssignName) and elt.name == name)
)
for elt in get_all_elements(target)
)
for target in node.targets
)

return is_defined_so_far or any(
is_defined(name, child) for child in node.get_children()
)


def get_inverse_comparator(op: str) -> str:
"""Returns the inverse comparator given a comparator.
Expand Down
Loading

0 comments on commit 4f89e7d

Please sign in to comment.