diff --git a/ChangeLog b/ChangeLog index 6bc62e7479..147a2f9d07 100644 --- a/ChangeLog +++ b/ChangeLog @@ -18,6 +18,15 @@ Release date: TBA +What's New in astroid 2.15.7? +============================= +Release date: 2023-07-08 + +* Fix a crash when inferring a ``typing.TypeVar`` call. + + Closes pylint-dev/pylint#8802 + + What's New in astroid 2.15.6? ============================= Release date: 2023-07-08 diff --git a/astroid/brain/brain_typing.py b/astroid/brain/brain_typing.py index e0a9dfd178..2cd5a32893 100644 --- a/astroid/brain/brain_typing.py +++ b/astroid/brain/brain_typing.py @@ -121,7 +121,9 @@ def looks_like_typing_typevar_or_newtype(node) -> bool: return False -def infer_typing_typevar_or_newtype(node, context_itton=None): +def infer_typing_typevar_or_newtype( + node: Call, context_itton: context.InferenceContext | None = None +) -> Iterator[ClassDef]: """Infer a typing.TypeVar(...) or typing.NewType(...) call.""" try: func = next(node.func.infer(context=context_itton)) @@ -137,7 +139,14 @@ def infer_typing_typevar_or_newtype(node, context_itton=None): raise UseInferenceDefault typename = node.args[0].as_string().strip("'") - node = extract_node(TYPING_TYPE_TEMPLATE.format(typename)) + node = ClassDef( + name=typename, + lineno=node.lineno, + col_offset=node.col_offset, + parent=node.parent, + end_lineno=node.end_lineno, + end_col_offset=node.end_col_offset, + ) return node.infer(context=context_itton) diff --git a/tests/brain/test_typing.py b/tests/brain/test_typing.py new file mode 100644 index 0000000000..4fdff77ae9 --- /dev/null +++ b/tests/brain/test_typing.py @@ -0,0 +1,27 @@ +# Licensed under the LGPL: https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html +# For details: https://github.com/PyCQA/astroid/blob/main/LICENSE +# Copyright (c) https://github.com/PyCQA/astroid/blob/main/CONTRIBUTORS.txt +# Licensed under the LGPL: https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html +# For details: https://github.com/pylint-dev/astroid/blob/main/LICENSE +# Copyright (c) https://github.com/pylint-dev/astroid/blob/main/CONTRIBUTORS.txt + +from astroid import builder, nodes + + +def test_infer_typevar() -> None: + """ + Regression test for: https://github.com/pylint-dev/pylint/issues/8802 + + Test that an inferred `typing.TypeVar()` call produces a `nodes.ClassDef` + node. + """ + assign_node = builder.extract_node( + """ + from typing import TypeVar + MyType = TypeVar('My.Type') + """ + ) + call = assign_node.value + inferred = next(call.infer()) + assert isinstance(inferred, nodes.ClassDef) + assert inferred.name == "My.Type"