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

Prevent a crash when inferring calls to str.format with invalid args #1866

Merged
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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
5 changes: 5 additions & 0 deletions ChangeLog
Expand Up @@ -29,6 +29,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