Skip to content

Impl PyAttributeError args #5805

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 1 commit into from
Jun 18, 2025
Merged

Conversation

youknowone
Copy link
Member

@youknowone youknowone commented Jun 18, 2025

Summary by CodeRabbit

  • Bug Fixes
    • Unified and improved error handling for missing attributes, providing clearer and more consistent error messages.
  • Tests
    • Updated tests related to attribute errors to expect successful execution instead of expected failures.

Copy link

coderabbitai bot commented Jun 18, 2025

Walkthrough

The updates unify the creation and handling of AttributeError exceptions across the codebase by introducing a new new_no_attribute_error method in the virtual machine. All relevant error-raising locations now use this method to generate attribute errors with contextual information. Corresponding tests are updated to expect passing behavior.

Changes

File(s) Change Summary
Lib/test/test_exceptions.py Removed @unittest.expectedFailure and comment from two tests, making them standard passing tests.
vm/src/builtins/descriptor.rs Replaced generic AttributeError creation with vm.new_no_attribute_error for missing slots.
vm/src/exceptions.rs Removed impl flag from #[pyexception] on PyAttributeError; added explicit impl with slot_init for attribute initialization.
vm/src/protocol/object.rs Replaced manual AttributeError creation with vm.new_no_attribute_error in attribute access and deletion.
vm/src/vm/method.rs Simplified missing attribute error handling to use vm.new_no_attribute_error.
vm/src/vm/vm_new.rs Added new_no_attribute_error method to VirtualMachine to create contextual AttributeError.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant VM
    participant PyObject
    participant Exception

    User->>PyObject: Access or delete attribute
    PyObject->>VM: Attribute not found
    VM->>VM: new_no_attribute_error(obj, attr_name)
    VM->>Exception: Create AttributeError with context
    Exception-->>User: Raise AttributeError with name and obj
Loading

Poem

In the warren of code, a new path appears,
Attribute errors now crystal clear!
No more patchwork, just one rabbit hop,
With context and clarity, we never stop.
🐇✨
Bugs beware, for this hop is neat—
AttributeError’s journey is now complete!


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 27b9b5e and 86cdbcc.

📒 Files selected for processing (6)
  • Lib/test/test_exceptions.py (0 hunks)
  • vm/src/builtins/descriptor.rs (1 hunks)
  • vm/src/exceptions.rs (1 hunks)
  • vm/src/protocol/object.rs (1 hunks)
  • vm/src/vm/method.rs (1 hunks)
  • vm/src/vm/vm_new.rs (1 hunks)
💤 Files with no reviewable changes (1)
  • Lib/test/test_exceptions.py
🚧 Files skipped from review as they are similar to previous changes (5)
  • vm/src/builtins/descriptor.rs
  • vm/src/vm/method.rs
  • vm/src/exceptions.rs
  • vm/src/vm/vm_new.rs
  • vm/src/protocol/object.rs
⏰ Context from checks skipped due to timeout of 90000ms (11)
  • GitHub Check: Run snippets and cpython tests (macos-latest)
  • GitHub Check: Run snippets and cpython tests (windows-latest)
  • GitHub Check: Run snippets and cpython tests on wasm-wasi
  • GitHub Check: Run rust tests (macos-latest)
  • GitHub Check: Run snippets and cpython tests (ubuntu-latest)
  • GitHub Check: Run rust tests (windows-latest)
  • GitHub Check: Check Rust code with rustfmt and clippy
  • GitHub Check: Run rust tests (ubuntu-latest)
  • GitHub Check: Check the WASM package and demo
  • GitHub Check: Run tests under miri
  • GitHub Check: Ensure compilation on various targets
✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 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.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

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

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (4)
vm/src/vm/vm_new.rs (1)

138-150: Consider propagating the set_attribute_error_context result and adding a doc-comment

set_attribute_error_context currently returns (), but if at some point it starts returning a PyResult<()> (mirroring CPython’s PyErr_SetObject–family helpers), this silent let _ = … pattern will hide errors.
Two low-friction improvements:

-        self.set_attribute_error_context(&attribute_error, obj, name);
+        // Propagate in case the signature ever changes in the future
+        self.set_attribute_error_context(&attribute_error, obj, name);

…and add a short rustdoc header so downstream contributors discover the helper quickly.

vm/src/builtins/descriptor.rs (1)

289-292: Avoid re-allocating the attribute name on every miss

member.name is already an interned &'static PyStrInterned.
Converting it into a fresh PyStr each time a slot miss occurs allocates and defeats interning.

-            vm.new_no_attribute_error(obj.clone(), vm.ctx.new_str(member.name.clone()))
+            vm.new_no_attribute_error(obj.clone(), vm.ctx.intern_str(member.name))

This keeps the PyStr shared and shaves a tiny allocation off a very hot path.

vm/src/exceptions.rs (1)

1263-1288: PyAttributeError.__init__ only recognises kwargs – consider positional fallback

CPython’s AttributeError accepts positional arguments and still sets name/obj when raised by the interpreter.
Right now a user doing:

raise AttributeError("msg", "attr", SomeObject)

will get name == None and obj == None.
Optionally consume args.args when kwargs are empty to stay CPython-compatible:

-    zelf.set_attr(
-        "name",
-        vm.unwrap_or_none(args.kwargs.get("name").cloned()),
-        vm,
-    )?;
+    let name_obj = if let Some(v) = args.kwargs.get("name") {
+        v.clone()
+    } else {
+        args.args.get(1).cloned().unwrap_or_else(|| vm.ctx.none())
+    };
+    zelf.set_attr("name", name_obj, vm)?;

Same for obj.

vm/src/protocol/object.rs (1)

188-194: Preserve original KeyError as the __cause__ of the generated AttributeError

KeyErrorAttributeError translation is correct, but the original exception information is lost.
Keeping it as the __cause__ makes debugging easier and mirrors CPython’s behaviour for exception chaining.

-                    vm.new_no_attribute_error(self.to_owned(), attr_name.to_owned())
+                    {
+                        let exc = vm.new_no_attribute_error(
+                            self.to_owned(),
+                            attr_name.to_owned(),
+                        );
+                        // pseudo-API: adjust to actual helper if available
+                        exc.set_cause(Some(e.clone()));
+                        exc
+                    }

If VirtualMachine::new_no_attribute_error already exposes a helper to attach a cause (or if the VM has a generic with_cause helper), prefer that instead of directly mutating the exception.
Otherwise, consider extending the helper so the call-sites stay concise.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 0dac02f and 27b9b5e.

📒 Files selected for processing (6)
  • Lib/test/test_exceptions.py (0 hunks)
  • vm/src/builtins/descriptor.rs (1 hunks)
  • vm/src/exceptions.rs (1 hunks)
  • vm/src/protocol/object.rs (1 hunks)
  • vm/src/vm/method.rs (1 hunks)
  • vm/src/vm/vm_new.rs (1 hunks)
💤 Files with no reviewable changes (1)
  • Lib/test/test_exceptions.py
⏰ Context from checks skipped due to timeout of 90000ms (11)
  • GitHub Check: Check the WASM package and demo
  • GitHub Check: Run snippets and cpython tests (ubuntu-latest)
  • GitHub Check: Run snippets and cpython tests on wasm-wasi
  • GitHub Check: Run snippets and cpython tests (windows-latest)
  • GitHub Check: Run rust tests (macos-latest)
  • GitHub Check: Run snippets and cpython tests (macos-latest)
  • GitHub Check: Run tests under miri
  • GitHub Check: Run rust tests (windows-latest)
  • GitHub Check: Check Rust code with rustfmt and clippy
  • GitHub Check: Run rust tests (ubuntu-latest)
  • GitHub Check: Ensure compilation on various targets
🔇 Additional comments (3)
vm/src/vm/method.rs (1)

80-83: Great simplification – logic now matches the new helper

Replacing the bespoke construction with vm.new_no_attribute_error removes duplication and guarantees the name/obj fields are populated consistently with the rest of the VM.

vm/src/protocol/object.rs (2)

197-199: Consistent use of new_no_attribute_error looks good

The fallback to AttributeError when the object has no __dict__ is now consistent with the rest of the codebase.


202-205: generic_getattr refactor is clear and idiomatic

Switching to ok_or_else with the new helper keeps the control flow straightforward and avoids duplicated formatting logic. No further action needed.

@youknowone youknowone merged commit a186a5a into RustPython:main Jun 18, 2025
11 of 12 checks passed
@youknowone youknowone deleted the attribute-error branch June 18, 2025 06:53
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.

1 participant