Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix crash inferring on NewType named with f-string #1400

Merged
merged 1 commit into from
Feb 19, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions ChangeLog
Original file line number Diff line number Diff line change
Expand Up @@ -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`.

Expand Down
4 changes: 4 additions & 0 deletions astroid/brain/brain_typing.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
Attribute,
Call,
Const,
JoinedStr,
Name,
NodeNG,
Subscript,
Expand Down Expand Up @@ -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))
Expand Down
19 changes: 18 additions & 1 deletion tests/unittest_brain.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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(
"""
Expand Down