Skip to content

Commit 4c56ba8

Browse files
Fix a crash when TYPE_CHECKING is used without importing it (#8435)
1 parent 74e6efc commit 4c56ba8

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
@@ -1918,7 +1918,10 @@ def in_type_checking_block(node: nodes.NodeNG) -> bool:
19181918
if isinstance(ancestor.test, nodes.Name):
19191919
if ancestor.test.name != "TYPE_CHECKING":
19201920
continue
1921-
maybe_import_from = ancestor.test.lookup(ancestor.test.name)[1][0]
1921+
lookup_result = ancestor.test.lookup(ancestor.test.name)[1]
1922+
if not lookup_result:
1923+
return False
1924+
maybe_import_from = lookup_result[0]
19221925
if (
19231926
isinstance(maybe_import_from, nodes.ImportFrom)
19241927
and maybe_import_from.modname == "typing"

tests/checkers/unittest_utils.py

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

448448

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

0 commit comments

Comments
 (0)