Skip to content

Implement PyComplex's __format__ function #5900

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 8 commits into from
Jul 4, 2025

Conversation

yt2b
Copy link
Contributor

@yt2b yt2b commented Jul 4, 2025

Summary

I've implemented PyComplex's __format__ function.
With this implementation, formatting complex number now works.

>>>>> f"{1+2j:.2f}"
'1.00+2.00j'

And following tests now pass.

  • test_complex.py
    • test_format
  • test_format.py
    • test_non_ascii
    • test_precision

Summary by CodeRabbit

  • New Features

    • Added support for formatting complex numbers with various format specifiers, including fixed-point, general, and exponential formats.
    • Introduced a new method for formatted string representation of complex numbers using Python's format protocol.
  • Bug Fixes

    • Improved error handling for unsupported format options in complex number formatting, providing clear error messages for zero-padding and alignment flag misuse.
  • Tests

    • Added comprehensive tests for complex number formatting, covering sign handling, alignment, fill characters, precision, and numeric formatting options.

Copy link
Contributor

coderabbitai bot commented Jul 4, 2025

"""

Walkthrough

Support for formatting complex numbers has been added across the codebase. The common crate now implements complex number formatting, including error handling for unsupported specifiers. The virtual machine's complex type supports the __format__ method. Tests have been added to verify complex formatting behavior, and error handling for new format errors is integrated.

Changes

Files/Paths Change Summary
common/Cargo.toml Marked num-complex as a workspace dependency.
common/src/format.rs Added complex number formatting support, new public method format_complex, and error variants.
extra_tests/snippets/builtin_format.py Added tests for complex number formatting with various format specifiers and options.
vm/src/builtins/complex.rs Implemented __format__ method for complex numbers using the new formatting logic.
vm/src/format.rs Extended error handling for new complex format spec errors (ZeroPadding, AlignmentFlag).

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant PyComplex
    participant FormatSpec
    participant VM

    User->>PyComplex: __format__(format_spec, vm)
    PyComplex->>FormatSpec: parse(format_spec)
    FormatSpec-->>PyComplex: FormatSpec instance or error
    PyComplex->>FormatSpec: format_complex(self.value)
    FormatSpec-->>PyComplex: Formatted string or FormatSpecError
    PyComplex->>VM: Return result or raise Python exception
Loading

Poem

In the warren, numbers twirl and spin,
Now complex forms can truly begin!
With signs and specs, and formats grand,
The rabbit’s code now understands.
Errors caught and tests abound—
Complex joy in every round!
🐇✨
"""

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 Clippy (1.86.0)
Updating git repository `https://github.com/youknowone/ferrilab`

error: failed to load source for dependency radium

Caused by:
Unable to update https://github.com/youknowone/ferrilab?branch=fix-nightly#4a301c3a

Caused by:
failed to create directory /usr/local/git/db/ferrilab-ed7d38936952b47e

Caused by:
Permission denied (os error 13)


📜 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 ecc7ae4 and 010797e.

📒 Files selected for processing (2)
  • common/src/format.rs (3 hunks)
  • vm/src/format.rs (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • vm/src/format.rs
  • common/src/format.rs
⏰ Context from checks skipped due to timeout of 90000ms (11)
  • GitHub Check: Run rust tests (macos-latest)
  • GitHub Check: Run snippets and cpython tests on wasm-wasi
  • GitHub Check: Run snippets and cpython tests (windows-latest)
  • GitHub Check: Run tests under miri
  • GitHub Check: Run snippets and cpython tests (ubuntu-latest)
  • GitHub Check: Check the WASM package and demo
  • GitHub Check: Run snippets and cpython tests (macos-latest)
  • GitHub Check: Run rust tests (windows-latest)
  • GitHub Check: Run rust tests (ubuntu-latest)
  • GitHub Check: Check Rust code with rustfmt and clippy
  • 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 @yt2b, 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 significantly enhances RustPython's capabilities by adding full support for formatting complex numbers via the __format__ protocol. This brings the behavior of complex number formatting closer to CPython, allowing for more consistent and expected string representations of complex numbers across different formatting options.

Highlights

  • Core Functionality: I have implemented the __format__ method for PyComplex objects, enabling standard Python formatting for complex numbers. This allows users to format complex numbers using f-strings or the format() built-in function, similar to how floats and integers are formatted.
  • Dependency Addition: To support complex number operations and formatting, I've added the num-complex crate as a dependency to the project.
  • Formatting Logic: New Rust functions (format_complex, format_complex_re_im, format_complex_float) have been added to common/src/format.rs to handle the intricate logic of formatting complex numbers, including sign handling, precision, and alignment for both real and imaginary parts.
  • Test Suite Updates: Existing @unittest.expectedFailure decorators have been removed from relevant tests in Lib/test/test_complex.py and Lib/test/test_format.py, as the new implementation now allows these tests to pass. Additionally, new comprehensive test cases for complex number formatting have been added to extra_tests/snippets/builtin_format.py to validate various formatting scenarios.
  • Error Handling: New FormatSpecError variants (ZeroPaddingNotAllowed, AlignmentFlagNotAllowed) have been introduced and mapped to Python ValueError exceptions to correctly handle unsupported format specifier options for complex numbers.
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

This pull request implements the __format__ function for PyComplex. I've found one high-severity issue related to correctness that should be addressed. Other than that, the code is well-structured and follows the existing patterns in the codebase.

@@ -617,6 +619,126 @@ impl FormatSpec {
}
}

pub fn format_complex(&self, num: &Complex64) -> Result<String, FormatSpecError> {

Choose a reason for hiding this comment

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

high

According to Python's documentation, specifying precision is not allowed for complex numbers when no presentation type is given. CPython raises a TypeError in this case.

For example, f"{1+2j:.3}" results in TypeError: precision not allowed in complex format specifier.

The current implementation incorrectly processes the precision instead of raising an error. You should add a check at the beginning of format_complex to disallow this.

        if self.format_type.is_none() && self.precision.is_some() {
            return Err(FormatSpecError::AlignmentFlagNotAllowed);
        }

Copy link
Contributor Author

Choose a reason for hiding this comment

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

In my local Python 3.13.0, f"{1+2j:.3}" results in '(1+2j)'.
Precision is ignored but TypeError isn't raised.

Comment on lines 832 to 833
ZeroPaddingNotAllowed,
AlignmentFlagNotAllowed,

Choose a reason for hiding this comment

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

medium

Consider renaming ZeroPaddingNotAllowed and AlignmentFlagNotAllowed to ZeroPadding and AlignmentFlag respectively, and updating the error messages accordingly. This would align better with the naming conventions used for other error types in this enum.

vm/src/format.rs Outdated
Comment on lines 43 to 47
FormatSpecError::ZeroPaddingNotAllowed => {
vm.new_value_error("Zero padding is not allowed in complex format specifier")
}
FormatSpecError::AlignmentFlagNotAllowed => {
vm.new_value_error("'=' alignment flag is not allowed in complex format specifier")

Choose a reason for hiding this comment

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

medium

The error messages for ZeroPaddingNotAllowed and AlignmentFlagNotAllowed could be more specific to complex number formatting to provide better clarity to the user.

@youknowone youknowone merged commit 0a59c1c into RustPython:main Jul 4, 2025
12 checks passed
@youknowone
Copy link
Member

Thank you!

@yt2b yt2b deleted the complex_format branch July 4, 2025 13:38
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