Skip to content

Commit b196941

Browse files
Fix crash inferring on NewType named with f-string (#1400)
1 parent 3174e0b commit b196941

File tree

3 files changed

+26
-1
lines changed

3 files changed

+26
-1
lines changed

ChangeLog

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,10 @@ Release date: TBA
2525

2626
Closes PyCQA/pylint#5771
2727

28+
* Fixed a crash inferring on a ``NewType`` named with an f-string.
29+
30+
Closes PyCQA/pylint#5770
31+
2832
* Add support for [attrs v21.3.0](https://github.com/python-attrs/attrs/releases/tag/21.3.0) which
2933
added a new `attrs` module alongside the existing `attr`.
3034

astroid/brain/brain_typing.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@
3131
Attribute,
3232
Call,
3333
Const,
34+
JoinedStr,
3435
Name,
3536
NodeNG,
3637
Subscript,
@@ -128,6 +129,9 @@ def infer_typing_typevar_or_newtype(node, context_itton=None):
128129
raise UseInferenceDefault
129130
if not node.args:
130131
raise UseInferenceDefault
132+
# Cannot infer from a dynamic class name (f-string)
133+
if isinstance(node.args[0], JoinedStr):
134+
raise UseInferenceDefault
131135

132136
typename = node.args[0].as_string().strip("'")
133137
node = extract_node(TYPING_TYPE_TEMPLATE.format(typename))

tests/unittest_brain.py

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -57,7 +57,11 @@
5757
from astroid import MANAGER, bases, builder, nodes, objects, test_utils, util
5858
from astroid.bases import Instance
5959
from astroid.const import PY37_PLUS
60-
from astroid.exceptions import AttributeInferenceError, InferenceError
60+
from astroid.exceptions import (
61+
AttributeInferenceError,
62+
InferenceError,
63+
UseInferenceDefault,
64+
)
6165
from astroid.nodes.node_classes import Const
6266
from astroid.nodes.scoped_nodes import ClassDef
6367

@@ -1660,6 +1664,19 @@ def test_typing_types(self) -> None:
16601664
inferred = next(node.infer())
16611665
self.assertIsInstance(inferred, nodes.ClassDef, node.as_string())
16621666

1667+
def test_typing_type_without_tip(self):
1668+
"""Regression test for https://github.com/PyCQA/pylint/issues/5770"""
1669+
node = builder.extract_node(
1670+
"""
1671+
from typing import NewType
1672+
1673+
def make_new_type(t):
1674+
new_type = NewType(f'IntRange_{t}', t) #@
1675+
"""
1676+
)
1677+
with self.assertRaises(UseInferenceDefault):
1678+
astroid.brain.brain_typing.infer_typing_typevar_or_newtype(node.value)
1679+
16631680
def test_namedtuple_nested_class(self):
16641681
result = builder.extract_node(
16651682
"""

0 commit comments

Comments
 (0)