Skip to content

Commit

Permalink
Fix a crash when TYPE_CHECKING is used without importing it (#8435) (
Browse files Browse the repository at this point in the history
…#8436)

(cherry picked from commit 4c56ba8)

Co-authored-by: Jacob Walls <jacobtylerwalls@gmail.com>
  • Loading branch information
github-actions[bot] and jacobtylerwalls committed Mar 11, 2023
1 parent 8c3652a commit 575319b
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 1 deletion.
3 changes: 3 additions & 0 deletions doc/whatsnew/fragments/8434.bugfix
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
Fix a crash when ``TYPE_CHECKING`` is used without importing it.

Closes #8434
5 changes: 4 additions & 1 deletion pylint/checkers/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -1970,7 +1970,10 @@ def in_type_checking_block(node: nodes.NodeNG) -> bool:
if isinstance(ancestor.test, nodes.Name):
if ancestor.test.name != "TYPE_CHECKING":
continue
maybe_import_from = ancestor.test.lookup(ancestor.test.name)[1][0]
lookup_result = ancestor.test.lookup(ancestor.test.name)[1]
if not lookup_result:
return False
maybe_import_from = lookup_result[0]
if (
isinstance(maybe_import_from, nodes.ImportFrom)
and maybe_import_from.modname == "typing"
Expand Down
10 changes: 10 additions & 0 deletions tests/checkers/unittest_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -447,6 +447,16 @@ def test_if_typing_guard() -> None:
assert utils.is_typing_guard(code[3]) is False


def test_in_type_checking_block() -> None:
code = astroid.extract_node(
"""
if TYPE_CHECKING: # don't import this!
import math #@
"""
)
assert utils.in_type_checking_block(code) is False


def test_is_empty_literal() -> None:
list_node = astroid.extract_node("a = []")
assert utils.is_base_container(list_node.value)
Expand Down

0 comments on commit 575319b

Please sign in to comment.