Skip to content

Commit

Permalink
Prevent a crash when inferring calls to str.format with invalid args (
Browse files Browse the repository at this point in the history
  • Loading branch information
jacobtylerwalls authored and Pierre-Sassoulas committed Nov 19, 2022
1 parent b20dafc commit 5ce40b1
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 2 deletions.
5 changes: 5 additions & 0 deletions ChangeLog
Expand Up @@ -24,6 +24,11 @@ Release date: TBA

Refs PyCQA/pylint#5099

* Prevent a crash when inferring calls to ``str.format`` with inferred arguments
that would be invalid.

Closes #1856

* Infer the `length` argument of the ``random.sample`` function.

Refs PyCQA/pylint#7706
Expand Down
6 changes: 4 additions & 2 deletions astroid/brain/brain_builtin_inference.py
Expand Up @@ -954,8 +954,10 @@ def _infer_str_format_call(

try:
formatted_string = format_template.format(*pos_values, **keyword_values)
except (IndexError, KeyError):
# If there is an IndexError there are too few arguments to interpolate
except (IndexError, KeyError, TypeError, ValueError):
# IndexError: there are too few arguments to interpolate
# TypeError: Unsupported format string
# ValueError: Unknown format code
return iter([util.Uninferable])

return iter([nodes.const_factory(formatted_string)])
Expand Down
6 changes: 6 additions & 0 deletions tests/unittest_brain_builtin.py
Expand Up @@ -103,6 +103,12 @@ def test_string_format(self, format_string: str) -> None:
"""
"My name is {fname}, I'm {age}".format(fsname = "Daniel", age = 12)
""",
"""
"My unicode character is {:c}".format(None)
""",
"""
"My hex format is {:4x}".format('1')
""",
],
)
def test_string_format_uninferable(self, format_string: str) -> None:
Expand Down

0 comments on commit 5ce40b1

Please sign in to comment.