Skip to content

Commit e9db95b

Browse files
Fix '_infer_str_format_call' crash when the string it analyses are uninferable (#2024)
Closes pylint-dev/pylint#8109 (cherry picked from commit ccbdd3c)
1 parent c47d3b9 commit e9db95b

File tree

3 files changed

+26
-2
lines changed

3 files changed

+26
-2
lines changed

ChangeLog

+3
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,9 @@ What's New in astroid 2.14.2?
1212
=============================
1313
Release date: TBA
1414

15+
* '_infer_str_format_call' won't crash anymore when the string it analyses are uninferable.
16+
17+
Closes PyCQA/pylint#8109
1518

1619

1720
What's New in astroid 2.14.1?

astroid/brain/brain_builtin_inference.py

+3-1
Original file line numberDiff line numberDiff line change
@@ -928,7 +928,9 @@ def _infer_str_format_call(
928928
"""Return a Const node based on the template and passed arguments."""
929929
call = arguments.CallSite.from_call(node, context=context)
930930
if isinstance(node.func.expr, nodes.Name):
931-
value: nodes.Const = helpers.safe_infer(node.func.expr)
931+
value: nodes.Const | None = helpers.safe_infer(node.func.expr)
932+
if value is None:
933+
return iter([util.Uninferable])
932934
else:
933935
value = node.func.expr
934936

tests/unittest_brain_builtin.py

+20-1
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
import pytest
1010

1111
from astroid import nodes, objects, util
12-
from astroid.builder import _extract_single_node
12+
from astroid.builder import _extract_single_node, extract_node
1313

1414

1515
class BuiltinsTest(unittest.TestCase):
@@ -127,3 +127,22 @@ def test_string_format_with_specs(self) -> None:
127127
inferred = next(node.infer())
128128
assert isinstance(inferred, nodes.Const)
129129
assert inferred.value == "My name is Daniel, I'm 12.00"
130+
131+
def test_string_format_in_dataclass_pylint8109(self) -> None:
132+
"""https://github.com/PyCQA/pylint/issues/8109"""
133+
function_def = extract_node(
134+
"""
135+
from dataclasses import dataclass
136+
137+
@dataclass
138+
class Number:
139+
amount: int | float
140+
round: int = 2
141+
142+
def __str__(self): #@
143+
number_format = "{:,.%sf}" % self.round
144+
return number_format.format(self.amount).rstrip("0").rstrip(".")
145+
"""
146+
)
147+
inferit = function_def.infer_call_result(function_def, context=None)
148+
assert [a.name for a in inferit] == [util.Uninferable]

0 commit comments

Comments
 (0)