Skip to content

Add BaseException.add_note() and __notes__ attribute support - #6252

Merged
youknowone merged 2 commits into
RustPython:mainfrom
ever0de:add-base-exception-notes-support
Nov 14, 2025
Merged

youknowone merged 2 commits into
RustPython:mainfrom
ever0de:add-base-exception-notes-support

Conversation

@ever0de

@ever0de ever0de commented Nov 13, 2025 •

Copy link
Copy Markdown
Contributor

Summary by CodeRabbit

  • New Features
    • Exceptions can now have notes attached, letting users add contextual messages to error objects for clearer debugging.
    • When adding a note, the runtime will create any needed internal storage automatically and append the note to the exception's notes list.

@coderabbitai

coderabbitai Bot commented Nov 13, 2025 •

Copy link
Copy Markdown
Contributor

Walkthrough

Extended builtins prelude imports to include PyList and added add_note(self, note: PyStrRef, vm: &VirtualMachine) -> PyResult<()> on PyRef<PyBaseException> to append PyStrRef notes into an exception's __notes__ list stored in its __dict__.

Changes

Cohort / File(s) Summary
Exception improvements
vm/src/exceptions.rs
Added PyList to builtins prelude exports; implemented add_note() on PyRef<PyBaseException> that ensures __dict__, ensures or creates __notes__ list, and appends a PyStrRef note, returning appropriate errors on type/attribute failures.

Sequence Diagram

sequenceDiagram
    participant Caller
    participant PyBaseException
    participant __dict__
    participant __notes__
    Note over PyBaseException, __notes__: add_note flow (new)

    Caller->>PyBaseException: add_note(note, vm)
    activate PyBaseException
    PyBaseException->>__dict__: get or create __dict__
    __dict__-->>PyBaseException: dict ref
    PyBaseException->>__notes__: get "__notes__" or create PyList
    __notes__-->>PyBaseException: list ref
    PyBaseException->>__notes__: append(note)
    __notes__-->>PyBaseException: append result
    PyBaseException-->>Caller: PyResult::Ok(())
    deactivate PyBaseException
Loading

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~8 minutes

  • Check add_note() error paths when __dict__ is missing or not a mapping.
  • Verify creation and append logic for __notes__ uses PyList correctly and respects reference/borrowing rules.
  • Confirm added PyList import does not conflict with existing exports.

Poem

🐰 I hop and nibble at error threads,
I tuck small notes by careful beds,
A list appears where worries dwell,
Each string a tiny captured spell,
Hooray — exceptions keep their threads!

Pre-merge checks and finishing touches

✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately describes the main changes: adding BaseException.add_note() method and notes attribute support as shown in the changeset.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

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

Comment @coderabbitai help to get the list of available commands and usage tips.

@ShaharNaveh ShaharNaveh left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🥳

@youknowone youknowone left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

👍

Comment thread vm/src/exceptions.rs Outdated
Comment on lines +662 to +670
let notes = dict
.get_item("__notes__", vm)
.or_else(|_| {
let new_notes = vm.ctx.new_list(vec![]);
dict.set_item("__notes__", new_notes.clone().into(), vm)?;
Ok(new_notes.into())
})?
.downcast::<PyList>()
.map_err(|_| vm.new_type_error("__notes__ must be a list"))?;

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Suggested change
let notes = dict
.get_item("__notes__", vm)
.or_else(|_| {
let new_notes = vm.ctx.new_list(vec![]);
dict.set_item("__notes__", new_notes.clone().into(), vm)?;
Ok(new_notes.into())
})?
.downcast::<PyList>()
.map_err(|_| vm.new_type_error("__notes__ must be a list"))?;
let notes = if let Ok(notes) = dict.get_item("__notes__", vm) {
notes
} else {
let new_notes = vm.ctx.new_list(vec![]);
dict.set_item("__notes__", new_notes.clone().into(), vm)?;
new_notes.into()
};
let notes = notes
.downcast::<PyList>()
.map_err(|_| vm.new_type_error("__notes__ must be a list"))?;

I’m a bit concerned about having side-effect code inside or_else.

@youknowone youknowone left a comment •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

left a suggestion about style

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

📜 Review details

Configuration used: Path: .coderabbit.yml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 95d11d9 and 9a1e58f.

📒 Files selected for processing (1)
  • vm/src/exceptions.rs (2 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
**/*.rs

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

**/*.rs: Format Rust code with the default rustfmt style (run cargo fmt)
Run clippy and fix any warnings or lints introduced by your changes
Follow Rust best practices for error handling and memory management

Files:

  • vm/src/exceptions.rs
{vm,stdlib}/**/*.rs

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Use RustPython macros (pyclass, pymodule, pyfunction, etc.) when implementing Python functionality in Rust

Files:

  • vm/src/exceptions.rs
🧠 Learnings (2)
📚 Learning: 2025-09-11T05:06:59.971Z
Learnt from: CR
Repo: RustPython/RustPython PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-09-11T05:06:59.971Z
Learning: Applies to {vm,stdlib}/**/*.rs : Use RustPython macros (`pyclass`, `pymodule`, `pyfunction`, etc.) when implementing Python functionality in Rust

Applied to files:

  • vm/src/exceptions.rs
📚 Learning: 2025-09-11T05:06:59.971Z
Learnt from: CR
Repo: RustPython/RustPython PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-09-11T05:06:59.971Z
Learning: Applies to Lib/**/*.py : Minimize modifications to CPython standard library files; only make minimal changes to work around RustPython limitations

Applied to files:

  • vm/src/exceptions.rs
🧬 Code graph analysis (1)
vm/src/exceptions.rs (3)
vm/src/object/core.rs (1)
  • dict (699-701)
vm/src/builtins/dict.rs (1)
  • dict (756-756)
vm/src/stdlib/functools.rs (1)
  • dict (180-182)
⏰ 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: 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 snippets and cpython tests (macos-latest)
  • GitHub Check: Check Rust code with clippy
  • GitHub Check: Run rust tests (ubuntu-latest)
  • GitHub Check: Run rust tests (windows-latest)
  • GitHub Check: Run rust tests (macos-latest)
  • GitHub Check: Ensure compilation on various targets
  • GitHub Check: auto_format
🔇 Additional comments (1)
vm/src/exceptions.rs (1)

7-7: LGTM: Import addition is necessary and properly placed.

The PyList import is required for the new add_note method implementation and is correctly added in alphabetical order.

Comment thread vm/src/exceptions.rs
Comment on lines +655 to +676
#[pymethod]
fn add_note(self, note: PyStrRef, vm: &VirtualMachine) -> PyResult<()> {
let dict = self
.as_object()
.dict()
.ok_or_else(|| vm.new_attribute_error("Exception object has no __dict__"))?;

let notes = if let Ok(notes) = dict.get_item("__notes__", vm) {
notes
} else {
let new_notes = vm.ctx.new_list(vec![]);
dict.set_item("__notes__", new_notes.clone().into(), vm)?;
new_notes.into()
};

let notes = notes
.downcast::<PyList>()
.map_err(|_| vm.new_type_error("__notes__ must be a list"))?;

notes.borrow_vec_mut().push(note.into());
Ok(())
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🔴 Critical

🧩 Analysis chain

Implementation looks solid, but consider more explicit error handling.

The add_note method correctly implements the expected behavior:

  • Type safety via PyStrRef parameter
  • Proper __dict__ validation
  • Creates __notes__ list if missing
  • Type checks the existing __notes__

However, the if-let pattern on lines 662-668 treats all errors from dict.get_item() as "key not found," which could mask legitimate errors (e.g., if a custom __getitem__ raises an exception). While this is acceptable for typical use cases, consider using get_item_opt() or similar if available to distinguish between "key not found" and "error occurred."

Verify whether PyDict provides a method to distinguish between "key not found" and "error during lookup":


🏁 Script executed:

#!/bin/bash
# Search for PyDict methods that might distinguish between missing keys and errors
ast-grep --pattern 'impl PyDict {
  $$$
  fn get_item$_($$$) {
    $$$
  }
  $$$
}'

# Also search for any opt/option variants
rg -nP --type=rust '\bget_item.*opt\b' vm/src/builtins/

Length of output: 743


🏁 Script executed:

#!/bin/bash
# Examine get_item_opt implementation
sed -n '573,620p' vm/src/builtins/dict.rs

# Also examine get_item implementation for comparison
sed -n '540,570p' vm/src/builtins/dict.rs

# Look at how add_note currently uses get_item
sed -n '655,676p' vm/src/exceptions.rs

Length of output: 197


🏁 Script executed:

#!/bin/bash
# Find and examine get_item_opt implementation
fd -e rs dict.rs | head -1 | xargs -I {} sed -n '570,620p' {}

# Find exceptions.rs and examine add_note method
fd -e rs exceptions.rs | head -1 | xargs -I {} sed -n '655,676p' {}

# Also look at get_item implementation for comparison
fd -e rs dict.rs | head -1 | xargs -I {} sed -n '540,575p' {}

Length of output: 3310


Replace get_item with get_item_opt to properly distinguish between missing keys and errors.

The review comment is correct. The get_item_opt method exists and returns PyResult<Option<PyObjectRef>>, distinguishing three cases:

  • Ok(Some(value)) for found keys
  • Ok(None) for missing keys
  • Err(e) for actual errors

The current implementation using get_item masks all errors (including legitimate ones from custom __getitem__) as "key not found". Use get_item_opt instead:

let notes = if let Some(notes) = dict.get_item_opt("__notes__", vm)? {
    notes
} else {
    let new_notes = vm.ctx.new_list(vec![]);
    dict.set_item("__notes__", new_notes.clone().into(), vm)?;
    new_notes.into()
};

This properly propagates actual errors while handling missing keys correctly.

🤖 Prompt for AI Agents
In vm/src/exceptions.rs around lines 655 to 676, the code uses dict.get_item
which masks real errors as "missing key"; replace it with
dict.get_item_opt("__notes__", vm)? and handle the resulting Option by using the
contained value when Some(_) and creating + setting a new list on None, allowing
any Err to propagate via the ? operator; keep the subsequent downcast to PyList
and the push logic unchanged.

@youknowone youknowone left a comment

Copy link
Copy Markdown
Member

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 9ce8586 into RustPython:main Nov 14, 2025
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.

3 participants