From e1318d6647248dbf91cec361c53cdadc7979ff87 Mon Sep 17 00:00:00 2001 From: Jacob Walls Date: Fri, 18 Feb 2022 23:48:17 -0500 Subject: [PATCH] Fix crash inferring on NewType named with f-string --- ChangeLog | 4 ++++ astroid/brain/brain_typing.py | 4 ++++ tests/unittest_brain.py | 19 ++++++++++++++++++- 3 files changed, 26 insertions(+), 1 deletion(-) diff --git a/ChangeLog b/ChangeLog index bce6094b46..a57370c0da 100644 --- a/ChangeLog +++ b/ChangeLog @@ -25,6 +25,10 @@ Release date: TBA Closes PyCQA/pylint#5771 +* Fixed a crash inferring on a ``NewType`` named with an f-string. + + Closes PyCQA/pylint#5770 + * Add support for [attrs v21.3.0](https://github.com/python-attrs/attrs/releases/tag/21.3.0) which added a new `attrs` module alongside the existing `attr`. diff --git a/astroid/brain/brain_typing.py b/astroid/brain/brain_typing.py index 4f9cfdccef..680c3ec386 100644 --- a/astroid/brain/brain_typing.py +++ b/astroid/brain/brain_typing.py @@ -31,6 +31,7 @@ Attribute, Call, Const, + JoinedStr, Name, NodeNG, Subscript, @@ -128,6 +129,9 @@ def infer_typing_typevar_or_newtype(node, context_itton=None): raise UseInferenceDefault if not node.args: raise UseInferenceDefault + # Cannot infer from a dynamic class name (f-string) + if isinstance(node.args[0], JoinedStr): + raise UseInferenceDefault typename = node.args[0].as_string().strip("'") node = extract_node(TYPING_TYPE_TEMPLATE.format(typename)) diff --git a/tests/unittest_brain.py b/tests/unittest_brain.py index 7dfbdff23b..65fad677ca 100644 --- a/tests/unittest_brain.py +++ b/tests/unittest_brain.py @@ -57,7 +57,11 @@ from astroid import MANAGER, bases, builder, nodes, objects, test_utils, util from astroid.bases import Instance from astroid.const import PY37_PLUS -from astroid.exceptions import AttributeInferenceError, InferenceError +from astroid.exceptions import ( + AttributeInferenceError, + InferenceError, + UseInferenceDefault, +) from astroid.nodes.node_classes import Const from astroid.nodes.scoped_nodes import ClassDef @@ -1660,6 +1664,19 @@ def test_typing_types(self) -> None: inferred = next(node.infer()) self.assertIsInstance(inferred, nodes.ClassDef, node.as_string()) + def test_typing_type_without_tip(self): + """Regression test for https://github.com/PyCQA/pylint/issues/5770""" + node = builder.extract_node( + """ + from typing import NewType + + def make_new_type(t): + new_type = NewType(f'IntRange_{t}', t) #@ + """ + ) + with self.assertRaises(UseInferenceDefault): + astroid.brain.brain_typing.infer_typing_typevar_or_newtype(node.value) + def test_namedtuple_nested_class(self): result = builder.extract_node( """