Skip to content

Commit

Permalink
Fix '_infer_str_format_call' crash when the string it analyses are un…
Browse files Browse the repository at this point in the history
…inferable (#2024) (#2025)

Closes pylint-dev/pylint#8109

(cherry picked from commit ccbdd3c)

Co-authored-by: Pierre Sassoulas <pierre.sassoulas@gmail.com>
  • Loading branch information
github-actions[bot] and Pierre-Sassoulas authored Feb 12, 2023
1 parent c47d3b9 commit 4af956c
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 2 deletions.
3 changes: 3 additions & 0 deletions ChangeLog
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,9 @@ What's New in astroid 2.14.2?
=============================
Release date: TBA

* '_infer_str_format_call' won't crash anymore when the string it analyses are uninferable.

Closes PyCQA/pylint#8109


What's New in astroid 2.14.1?
Expand Down
4 changes: 3 additions & 1 deletion astroid/brain/brain_builtin_inference.py
Original file line number Diff line number Diff line change
Expand Up @@ -928,7 +928,9 @@ def _infer_str_format_call(
"""Return a Const node based on the template and passed arguments."""
call = arguments.CallSite.from_call(node, context=context)
if isinstance(node.func.expr, nodes.Name):
value: nodes.Const = helpers.safe_infer(node.func.expr)
value: nodes.Const | None = helpers.safe_infer(node.func.expr)
if value is None:
return iter([util.Uninferable])
else:
value = node.func.expr

Expand Down
21 changes: 20 additions & 1 deletion tests/unittest_brain_builtin.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
import pytest

from astroid import nodes, objects, util
from astroid.builder import _extract_single_node
from astroid.builder import _extract_single_node, extract_node


class BuiltinsTest(unittest.TestCase):
Expand Down Expand Up @@ -127,3 +127,22 @@ def test_string_format_with_specs(self) -> None:
inferred = next(node.infer())
assert isinstance(inferred, nodes.Const)
assert inferred.value == "My name is Daniel, I'm 12.00"

def test_string_format_in_dataclass_pylint8109(self) -> None:
"""https://github.com/PyCQA/pylint/issues/8109"""
function_def = extract_node(
"""
from dataclasses import dataclass
@dataclass
class Number:
amount: int | float
round: int = 2
def __str__(self): #@
number_format = "{:,.%sf}" % self.round
return number_format.format(self.amount).rstrip("0").rstrip(".")
"""
)
inferit = function_def.infer_call_result(function_def, context=None)
assert [a.name for a in inferit] == [util.Uninferable]

0 comments on commit 4af956c

Please sign in to comment.