Skip to content

[mypyc] feat: optimize f-string building from Final values #19611

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

Open
wants to merge 34 commits into
base: master
Choose a base branch
from

Conversation

BobTheBuidler
Copy link
Contributor

@BobTheBuidler BobTheBuidler commented Aug 7, 2025

We can do some extra constant folding in cases like this:

from typing import Final

BASE_URL: Final = "https://example.com"
PORT: Final = 1234

def get_url(endpoint: str) -> str:
    return f"{BASE_URL}:{PORT}/{endpoint}"

which should generate the same C code as

def get_url(endpoint: str) -> str:
    return f"https://example.com:1234/{endpoint}"

This PR makes it so.

@BobTheBuidler BobTheBuidler changed the title WIP [mypyc] optimize f-string building [mypyc] feat: optimize f-string building from Final values Aug 11, 2025
@BobTheBuidler BobTheBuidler marked this pull request as ready for review August 11, 2025 22:05
@BobTheBuidler
Copy link
Contributor Author

This PR is now ready for review.

@BobTheBuidler
Copy link
Contributor Author

BobTheBuidler commented Aug 11, 2025

This can probably be extended later on for non-final values that type check as Literals ex:

def test():
    abcd = "abcd"
    efgh = "efgh"
    if some_check():
        ijkl = "ijkl0"
        some_numbers = 123
        return f"{abcd}{efgh}{ijkl}{some_numbers}{some_fn()}"
    else:
        ijkl = "ijkl1"
        some_numbers = 456
        return f"{abcd}{efgh}{ijkl}{some_numbers}{some_fn()}"

But I think that goes beyond the scope of this PR. Once we merge this it will be easy to modify the literal helper fn.

Copy link
Collaborator

@JukkaL JukkaL left a comment

Choose a reason for hiding this comment

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

Thanks for the PR! The approach looks good, just a few minor comments.

@BobTheBuidler
Copy link
Contributor Author

Thanks for your feedbacks. Tests added, comment removed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants