Skip to content
Open
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
28 changes: 24 additions & 4 deletions astroid/brain/brain_builtin_inference.py
Original file line number Diff line number Diff line change
Expand Up @@ -842,15 +842,35 @@ def infer_str(node, context: InferenceContext | None = None) -> nodes.Const:

:param nodes.Call node: str() call to infer
:param context.InferenceContext: node context
:rtype nodes.Const: a Const containing an empty string
:rtype nodes.Const:
a Const containing a stringified value of str() call if possible, else an empty string
"""
call = arguments.CallSite.from_call(node, context=context)
if call.keyword_arguments:
raise UseInferenceDefault("TypeError: str() must take no keyword arguments")

fallback = nodes.Const("")

if not call.positional_arguments:
return fallback

# Accept only if all inferred values resolve to the same string
candidates: set[str] = set()
try:
return nodes.Const("")
except (AstroidTypeError, InferenceError) as exc:
raise UseInferenceDefault(str(exc)) from exc
for inferred in call.positional_arguments[0].infer(context=context):
if not isinstance(inferred, nodes.Const):
return fallback

try:
candidates.add(str(inferred.value))
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should we only run str() if the value is a builtin? I wouldn't want a more involved str() implementation from user code to run (we should keep pylint static).

except ValueError:
return fallback
except InferenceError:
return fallback

if len(candidates) == 1:
return nodes.Const(candidates.pop())
Comment on lines +871 to +872
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This seems like an unnecessary source of indeterminism.

return fallback


def infer_int(node, context: InferenceContext | None = None):
Expand Down
32 changes: 32 additions & 0 deletions tests/brain/test_brain.py
Original file line number Diff line number Diff line change
Expand Up @@ -1407,6 +1407,7 @@ def test_infer_str() -> None:
str(s) #@
str('a') #@
str(some_object()) #@
str(7**10000) #@
""")
for node in ast_nodes:
inferred = next(node.infer())
Expand All @@ -1420,6 +1421,37 @@ def test_infer_str() -> None:
assert inferred.qname() == "builtins.str"


def test_infer_str_const() -> None:
ast_nodes = astroid.extract_node("""
str('') #@
str('a') #@
str(1) #@
str(True) #@
str(False) #@
str(None) #@
str(4.33) #@
str(...) #@
str(2 + 2) #@
str() #@
str(int) #@
str(2 if unknown() else 3) #@
Copy link
Copy Markdown
Member

@jacobtylerwalls jacobtylerwalls Apr 1, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think we should add a test ensuring user __str__ doesn't run:

class StrWillFail:
    def __str__(self):
        raise RuntimeError

str(StrWillFail()) #@

""")

inferred = list(node.inferred()[0].value for node in ast_nodes)
assert inferred[0] == ""
assert inferred[1] == "a"
assert inferred[2] == "1"
assert inferred[3] == "True"
assert inferred[4] == "False"
assert inferred[5] == "None"
assert inferred[6] == "4.33"
assert inferred[7] == "Ellipsis"
assert inferred[8] == "4"
assert inferred[9] == ""
assert inferred[10] == ""
assert inferred[11] == ""


def test_infer_int() -> None:
ast_nodes = astroid.extract_node("""
int(0) #@
Expand Down
Loading