Skip to content

Fix constant folding of "..." + "".join(seq * n) - #8021

Merged
scoder merged 2 commits into
cython:masterfrom
orztrickster:fix-stale-constant-of-multiplied-sequence
Oct 2, 2026
Merged

scoder merged 2 commits into
cython:masterfrom
orztrickster:fix-stale-constant-of-multiplied-sequence

Conversation

@orztrickster

Copy link
Copy Markdown
Contributor
def f(n):
    return "a" + "".join(["x"] * n)

f(3) returns 'ax' instead of 'axxx'. The same happens with * 2, * 0 and tuples.

This fixes it and adds a test.

@scoder scoder left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Thanks.

Comment thread Cython/Compiler/Optimize.py Outdated
else:
sequence_node.mult_factor = factor
if sequence_node.mult_factor is None:
sequence_node.calculate_constant_result()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

You cannot just call .calculate_constant_result() of a node because it's not guaranteed to succeed. self._calculate_const() does it correctly, but it also evaluates the whole node subtree, which should only be done once (although it doesn't hurt to repeat it).

I'd start by folding the two cases here into the if-blocks above and see where that leaves us.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Thanks, updated.

@scoder scoder added this to the 3.3.1 milestone Oct 2, 2026
@scoder
scoder enabled auto-merge (squash) October 2, 2026 10:50
@scoder
scoder merged commit d1c9bbc into cython:master Oct 2, 2026
110 of 115 checks passed
@scoder

scoder commented Oct 2, 2026

Copy link
Copy Markdown
Contributor

Thanks again.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants