Skip to content

Commit 89dfb48

Browse files
authored
Fix a crash when inferring a typing.TypeVar call. (#2239)
Closes pylint-dev/pylint#8802
1 parent 623482b commit 89dfb48

File tree

3 files changed

+45
-3
lines changed

3 files changed

+45
-3
lines changed

ChangeLog

+10-1
Original file line numberDiff line numberDiff line change
@@ -195,10 +195,19 @@ Release date: TBA
195195
Refs #2204
196196

197197

198-
What's New in astroid 2.15.6?
198+
What's New in astroid 2.15.7?
199199
=============================
200200
Release date: TBA
201201

202+
* Fix a crash when inferring a ``typing.TypeVar`` call.
203+
204+
Closes pylint-dev/pylint#8802
205+
206+
207+
What's New in astroid 2.15.6?
208+
=============================
209+
Release date: 2023-07-08
210+
202211
* Harden ``get_module_part()`` against ``"."``.
203212

204213
Closes pylint-dev/pylint#8749

astroid/brain/brain_typing.py

+11-2
Original file line numberDiff line numberDiff line change
@@ -118,7 +118,9 @@ def looks_like_typing_typevar_or_newtype(node) -> bool:
118118
return False
119119

120120

121-
def infer_typing_typevar_or_newtype(node, context_itton=None):
121+
def infer_typing_typevar_or_newtype(
122+
node: Call, context_itton: context.InferenceContext | None = None
123+
) -> Iterator[ClassDef]:
122124
"""Infer a typing.TypeVar(...) or typing.NewType(...) call."""
123125
try:
124126
func = next(node.func.infer(context=context_itton))
@@ -134,7 +136,14 @@ def infer_typing_typevar_or_newtype(node, context_itton=None):
134136
raise UseInferenceDefault
135137

136138
typename = node.args[0].as_string().strip("'")
137-
node = extract_node(TYPING_TYPE_TEMPLATE.format(typename))
139+
node = ClassDef(
140+
name=typename,
141+
lineno=node.lineno,
142+
col_offset=node.col_offset,
143+
parent=node.parent,
144+
end_lineno=node.end_lineno,
145+
end_col_offset=node.end_col_offset,
146+
)
138147
return node.infer(context=context_itton)
139148

140149

tests/brain/test_typing.py

+24
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
# Licensed under the LGPL: https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html
2+
# For details: https://github.com./pylint-dev/astroid/blob/main/LICENSE
3+
# Copyright (c) https://github.com./pylint-dev/astroid/blob/main/CONTRIBUTORS.txt
4+
5+
from astroid import builder, nodes
6+
7+
8+
def test_infer_typevar() -> None:
9+
"""
10+
Regression test for: https://github.com./pylint-dev/pylint/issues/8802
11+
12+
Test that an inferred `typing.TypeVar()` call produces a `nodes.ClassDef`
13+
node.
14+
"""
15+
assign_node = builder.extract_node(
16+
"""
17+
from typing import TypeVar
18+
MyType = TypeVar('My.Type')
19+
"""
20+
)
21+
call = assign_node.value
22+
inferred = next(call.infer())
23+
assert isinstance(inferred, nodes.ClassDef)
24+
assert inferred.name == "My.Type"

0 commit comments

Comments
 (0)