-
Notifications
You must be signed in to change notification settings - Fork 1.3k
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
Conversation
""" WalkthroughSupport for formatting complex numbers has been added across the codebase. The Changes
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
Poem
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)
error: failed to load source for dependency Caused by: Caused by: Caused by: 📜 Recent review detailsConfiguration used: .coderabbit.yml 📒 Files selected for processing (2)
🚧 Files skipped from review as they are similar to previous changes (2)
⏰ Context from checks skipped due to timeout of 90000ms (11)
✨ Finishing Touches
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. 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed 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)
Other keywords and placeholders
Documentation and Community
|
There was a problem hiding this 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 forPyComplex
objects, enabling standard Python formatting for complex numbers. This allows users to format complex numbers using f-strings or theformat()
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 tocommon/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 inLib/test/test_complex.py
andLib/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 toextra_tests/snippets/builtin_format.py
to validate various formatting scenarios. - Error Handling: New
FormatSpecError
variants (ZeroPaddingNotAllowed
,AlignmentFlagNotAllowed
) have been introduced and mapped to PythonValueError
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
-
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. ↩
There was a problem hiding this 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> { |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
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);
}
There was a problem hiding this comment.
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.
common/src/format.rs
Outdated
ZeroPaddingNotAllowed, | ||
AlignmentFlagNotAllowed, |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
vm/src/format.rs
Outdated
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") |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Thank you! |
Summary
I've implemented PyComplex's __format__ function.
With this implementation, formatting complex number now works.
And following tests now pass.
Summary by CodeRabbit
New Features
Bug Fixes
Tests