Skip to content

Commit e6f0bc5

Browse files
Fix used-before-assignment if conditional imports guarded again when used (#7980)
1 parent 4a5f5be commit e6f0bc5

File tree

4 files changed

+17
-5
lines changed

4 files changed

+17
-5
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
Prevent ``used-before-assignment`` when imports guarded by ``if TYPE_CHECKING``
2+
are guarded again when used.
3+
4+
Closes #7979

pylint/checkers/variables.py

+1
Original file line numberDiff line numberDiff line change
@@ -2193,6 +2193,7 @@ def _is_variable_violation(
21932193
isinstance(defstmt, (nodes.Import, nodes.ImportFrom))
21942194
and isinstance(defstmt.parent, nodes.If)
21952195
and in_type_checking_block(defstmt)
2196+
and not in_type_checking_block(node)
21962197
):
21972198
defstmt_parent = defstmt.parent
21982199

tests/functional/u/used/used_before_assignment_typing.py

+7
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
if True: # pylint: disable=using-constant-test
99
import math
1010
import datetime
11+
from urllib.request import urlopen
1112

1213
class MyClass:
1314
"""Type annotation or default values for first level methods can't refer to their own class"""
@@ -101,3 +102,9 @@ class VariableAnnotationsGuardedByTypeChecking: # pylint: disable=too-few-publi
101102
def print_date(self, date) -> None:
102103
date: datetime.date = date
103104
print(date)
105+
106+
107+
class ConditionalImportGuardedWhenUsed: # pylint: disable=too-few-public-methods
108+
"""Conditional imports also guarded by TYPE_CHECKING when used."""
109+
if TYPE_CHECKING:
110+
print(urlopen)
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
1-
undefined-variable:16:21:16:28:MyClass.incorrect_typing_method:Undefined variable 'MyClass':UNDEFINED
2-
undefined-variable:21:26:21:33:MyClass.incorrect_nested_typing_method:Undefined variable 'MyClass':UNDEFINED
3-
undefined-variable:26:20:26:27:MyClass.incorrect_default_method:Undefined variable 'MyClass':UNDEFINED
4-
used-before-assignment:87:35:87:39:MyFourthClass.is_close:Using variable 'math' before assignment:HIGH
5-
used-before-assignment:99:20:99:28:VariableAnnotationsGuardedByTypeChecking:Using variable 'datetime' before assignment:HIGH
1+
undefined-variable:17:21:17:28:MyClass.incorrect_typing_method:Undefined variable 'MyClass':UNDEFINED
2+
undefined-variable:22:26:22:33:MyClass.incorrect_nested_typing_method:Undefined variable 'MyClass':UNDEFINED
3+
undefined-variable:27:20:27:27:MyClass.incorrect_default_method:Undefined variable 'MyClass':UNDEFINED
4+
used-before-assignment:88:35:88:39:MyFourthClass.is_close:Using variable 'math' before assignment:HIGH
5+
used-before-assignment:100:20:100:28:VariableAnnotationsGuardedByTypeChecking:Using variable 'datetime' before assignment:HIGH

0 commit comments

Comments
 (0)