Skip to content

Commit a7202b1

Browse files
Fix Python 3.12 generic type syntax (#10135) (#10146)
(cherry picked from commit be1968e) Co-authored-by: Marzuk Rashid <[email protected]>
1 parent 90cb29d commit a7202b1

File tree

5 files changed

+23
-6
lines changed

5 files changed

+23
-6
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
Fix false positives for ``undefined-variable`` for classes using Python 3.12
2+
generic type syntax.
3+
4+
Closes #9335

pylint/checkers/variables.py

+15-1
Original file line numberDiff line numberDiff line change
@@ -1768,6 +1768,11 @@ def _should_node_be_skipped(
17681768
if utils.is_ancestor_name(consumer.node, node) or (
17691769
not is_start_index and self._ignore_class_scope(node)
17701770
):
1771+
if any(
1772+
node.name == param.name.name for param in consumer.node.type_params
1773+
):
1774+
return False
1775+
17711776
return True
17721777

17731778
# Ignore inner class scope for keywords in class definition
@@ -1978,7 +1983,9 @@ def _check_consumer(
19781983
)
19791984
return (VariableVisitConsumerAction.RETURN, found_nodes)
19801985

1981-
elif isinstance(defstmt, nodes.ClassDef):
1986+
elif (
1987+
isinstance(defstmt, nodes.ClassDef) and defnode not in defframe.type_params
1988+
):
19821989
return self._is_first_level_self_reference(node, defstmt, found_nodes)
19831990

19841991
elif isinstance(defnode, nodes.NamedExpr):
@@ -2357,6 +2364,13 @@ def _is_variable_violation(
23572364
maybe_before_assign = defnode.value is node or any(
23582365
anc is defnode.value for anc in node.node_ancestors()
23592366
)
2367+
elif (
2368+
isinstance(defframe, nodes.ClassDef)
2369+
and defnode in defframe.type_params
2370+
):
2371+
# Generic on parent class:
2372+
# class Child[_T](Parent[_T])
2373+
maybe_before_assign = False
23602374

23612375
return maybe_before_assign, annotation_return, use_outer_definition
23622376

tests/functional/g/generic_class_syntax_py312.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
class Entity[_T: float]:
33
last_update: int | None = None
44

5-
def __init__(self, data: _T) -> None: # [undefined-variable] # false-positive
5+
def __init__(self, data: _T) -> None:
66
self.data = data
77

88

@@ -28,6 +28,6 @@ def __init__(self):
2828
self.update_interval = 0
2929

3030

31-
class Child[_T](Parent[_T]): # [undefined-variable] # false-positive
31+
class Child[_T](Parent[_T]):
3232
def func(self):
3333
self.update_interval = None

tests/functional/g/generic_class_syntax_py312.txt

-2
This file was deleted.

tests/functional/u/undefined/undefined_variable_py312.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -4,4 +4,5 @@ def f[T](a: T) -> T:
44
print(a)
55

66
class ChildClass[T, *Ts, **P]:
7-
...
7+
def __init__(self, value: T):
8+
self.value = value

0 commit comments

Comments
 (0)