Skip to content

fix(format): isolate special grouping rule to sign-aware zero-padding #5924

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

Merged
merged 2 commits into from
Jul 10, 2025

Conversation

ever0de
Copy link
Contributor

@ever0de ever0de commented Jul 9, 2025

Summary by CodeRabbit

  • Bug Fixes

    • Improved number formatting to ensure that padding is applied to the left of the entire formatted number when using width and comma grouping, matching expected behavior.
  • Tests

    • Added tests to verify correct placement of padding and grouping separators for formatted integers.

Summary by CodeRabbit

  • Bug Fixes

    • Improved number formatting to correctly handle grouping separators and zero-padding based on alignment settings.
  • Tests

    • Added tests to validate integer formatting with width, zero-padding, and grouping separators, ensuring consistent and expected output.

Copy link
Contributor

coderabbitai bot commented Jul 9, 2025

Walkthrough

The update refines the logic for inserting grouping separators and zero-padding in integer formatting, ensuring correct behavior when width, zero-padding, and alignment are combined. The changes specifically adjust the calculation of displayed digit count based on alignment and padding, and introduce new tests to verify compliance with CPython's formatting rules.

Changes

File(s) Change Summary
common/src/format.rs Refined logic in add_magnitude_separators for disp_digit_cnt calculation, adding alignment check to zero-padding.
common/src/format.rs (tests) Added three new test functions verifying integer formatting with width, grouping separators, zero-padding, and alignment.

Sequence Diagram(s)

sequenceDiagram
    participant Caller
    participant FormatSpec
    participant add_magnitude_separators

    Caller->>FormatSpec: format integer with width, grouping, zero-padding, alignment
    FormatSpec->>add_magnitude_separators: call with magnitude, width, fill, align
    add_magnitude_separators->>add_magnitude_separators: calculate disp_digit_cnt (consider fill and align)
    add_magnitude_separators-->>FormatSpec: return formatted string with correct padding/grouping
    FormatSpec-->>Caller: return formatted integer string
Loading

Possibly related PRs

Suggested reviewers

  • youknowone

Poem

In the warren where numbers hop and play,
Commas and padding now leap the right way.
With width and alignment, all in a row,
The integers march—see how they glow!
🐇✨
Grouped and padded, neat as can be,
This code brings joy to formatting, whee!


📜 Recent review details

Configuration used: .coderabbit.yml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 9a2d099 and 45576d9.

📒 Files selected for processing (1)
  • common/src/format.rs (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • common/src/format.rs
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (11)
  • GitHub Check: Run snippets and cpython tests (ubuntu-latest)
  • GitHub Check: Check the WASM package and demo
  • GitHub Check: Run snippets and cpython tests (windows-latest)
  • GitHub Check: Run snippets and cpython tests on wasm-wasi
  • GitHub Check: Run tests under miri
  • GitHub Check: Run rust tests (macos-latest)
  • GitHub Check: Run snippets and cpython tests (macos-latest)
  • GitHub Check: Run rust tests (ubuntu-latest)
  • GitHub Check: Check Rust code with rustfmt and clippy
  • GitHub Check: Run rust tests (windows-latest)
  • GitHub Check: Ensure compilation on various targets
✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

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

Summary of Changes

Hello @ever0de, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request addresses a long-standing bug (issue #5922) in number formatting within the format.rs module. The core problem was an incorrect interaction between width specifiers and grouping separators, particularly when zero-padding was not explicitly requested. My changes refactor the padding logic to ensure that width-based padding for non-zero-padded numbers correctly applies as external space padding, rather than influencing the internal digit count for grouping. This brings the formatting behavior in line with CPython's specification, improving the accuracy of f-string formatting for integers.

Highlights

  • Formatting Logic Refinement: I've modified the add_magnitude_separators function in common/src/format.rs to correctly handle width-based padding for numbers with grouping. The disp_digit_cnt calculation now differentiates between scenarios where zero-padding is explicitly requested (using the '0' flag) and when it is not. This ensures that width specifiers for non-zero-padded numbers apply as external space padding, rather than affecting the internal digit count for grouping.
  • Test Coverage: I've added a new Rust test case, test_format_int_width_and_grouping, in common/src/format.rs to specifically validate the fix for issue #5922. Additionally, a corresponding Python snippet test has been included in extra_tests/snippets/builtin_format.py to confirm that f"{1234:10,}" produces the expected space-padded output, aligning with CPython's behavior.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point in your pull request via creating an issue comment (i.e. comment on the pull request page) using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in issue comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist is currently in preview and may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments to provide feedback.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

Copy link

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

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

Code Review

The pull request addresses issue #5922 by ensuring correct padding for numbers with width and grouping in the formatting logic. It introduces a check for zero-padding to determine how width is calculated when grouping separators are present. Additionally, it includes a new test case to validate the fix and an assertion in a python test file.

Comment on lines 439 to 446
let magnitude_len = magnitude_str.len();
let width = self.width.unwrap_or(magnitude_len) as i32 - prefix.len() as i32;
let disp_digit_cnt = cmp::max(width, magnitude_len as i32);

let disp_digit_cnt = if zero_padding {
let width = self.width.unwrap_or(magnitude_len) as i32 - prefix.len() as i32;
cmp::max(width, magnitude_len as i32)
} else {
magnitude_len as i32
};

Choose a reason for hiding this comment

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

medium

The magnitude_len variable is declared on line 439 but not used when zero_padding is false, consider moving the declaration inside the if zero_padding block to avoid confusion and improve readability.

                let disp_digit_cnt = if zero_padding {
                    let width = self.width.unwrap_or(magnitude_len) as i32 - prefix.len() as i32;
                    cmp::max(width, magnitude_len as i32)
                } else {
                    let magnitude_len = magnitude_str.len();
                    magnitude_len as i32
                };

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I'll keep it as is, since magnitude_len is used in both branches.

@youknowone
Copy link
Member

In #5922, @yt2b mentioned they would investigate this issue:

I'll investigate the cause.

There’s no strict rule about claiming issues, but I hope this is respected as a matter of common courtesy for enough days.

@ever0de
Copy link
Contributor Author

ever0de commented Jul 9, 2025

Oh, I am so sorry. I realize now that I misunderstood and mistook you for a maintainer.
I'm closing this PR and will find another issue.
My apologies for the mistake.

@ever0de ever0de closed this Jul 9, 2025
@youknowone youknowone reopened this Jul 9, 2025
@youknowone
Copy link
Member

@ever0de could you rebase this patch if the zero-padding handling is a missing feature of #5927?

@ever0de

This comment was marked as resolved.

@ever0de
Copy link
Contributor Author

ever0de commented Jul 10, 2025

I can update the code to use this condition:

let disp_digit_cnt = if self.fill == Some('0'.into())
    && self.align == Some(FormatAlign::AfterSign)
{
// ...

EDIT)
And to follow up, I've found the exact test case that proves why my previous logic (checking only for fill == '0') was incomplete. The test below would have failed with that implementation:

// CPython behavior: f'{1234:0>10,}' results in "000001,234"
let spec = FormatSpec::parse("0>10,").unwrap();
let result = spec.format_int(&BigInt::from(1234)).unwrap();
assert_eq!(result, "000001,234");

I will now patch the code to check for both conditions (AfterSign && '0') to handle this correctly.

@ever0de ever0de force-pushed the fix/format-separator-padding branch from ddb39b8 to 9a2d099 Compare July 10, 2025 09:14
@ever0de ever0de changed the title fix(format): ensure correct padding for numbers with width and grouping fix(format): Isolate special grouping rule to sign-aware zero-padding Jul 10, 2025
@ever0de ever0de changed the title fix(format): Isolate special grouping rule to sign-aware zero-padding fix(format): isolate special grouping rule to sign-aware zero-padding Jul 10, 2025
Copy link
Member

@youknowone youknowone left a comment

Choose a reason for hiding this comment

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

Thank you!

@youknowone youknowone merged commit 4c75230 into RustPython:main Jul 10, 2025
12 checks passed
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