Skip to content

Commit 575319b

Browse files
Fix a crash when TYPE_CHECKING is used without importing it (#8435) (#8436)
(cherry picked from commit 4c56ba8) Co-authored-by: Jacob Walls <[email protected]>
1 parent 8c3652a commit 575319b

File tree

3 files changed

+17
-1
lines changed

3 files changed

+17
-1
lines changed

doc/whatsnew/fragments/8434.bugfix

+3
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
Fix a crash when ``TYPE_CHECKING`` is used without importing it.
2+
3+
Closes #8434

pylint/checkers/utils.py

+4-1
Original file line numberDiff line numberDiff line change
@@ -1970,7 +1970,10 @@ def in_type_checking_block(node: nodes.NodeNG) -> bool:
19701970
if isinstance(ancestor.test, nodes.Name):
19711971
if ancestor.test.name != "TYPE_CHECKING":
19721972
continue
1973-
maybe_import_from = ancestor.test.lookup(ancestor.test.name)[1][0]
1973+
lookup_result = ancestor.test.lookup(ancestor.test.name)[1]
1974+
if not lookup_result:
1975+
return False
1976+
maybe_import_from = lookup_result[0]
19741977
if (
19751978
isinstance(maybe_import_from, nodes.ImportFrom)
19761979
and maybe_import_from.modname == "typing"

tests/checkers/unittest_utils.py

+10
Original file line numberDiff line numberDiff line change
@@ -447,6 +447,16 @@ def test_if_typing_guard() -> None:
447447
assert utils.is_typing_guard(code[3]) is False
448448

449449

450+
def test_in_type_checking_block() -> None:
451+
code = astroid.extract_node(
452+
"""
453+
if TYPE_CHECKING: # don't import this!
454+
import math #@
455+
"""
456+
)
457+
assert utils.in_type_checking_block(code) is False
458+
459+
450460
def test_is_empty_literal() -> None:
451461
list_node = astroid.extract_node("a = []")
452462
assert utils.is_base_container(list_node.value)

0 commit comments

Comments
 (0)