Repository navigation
Add BaseException.add_note() and __notes__ attribute support - #6252
Conversation
WalkthroughExtended builtins prelude imports to include Changes
Sequence DiagramsequenceDiagram
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
Estimated code review effort🎯 2 (Simple) | ⏱️ ~8 minutes
Poem
Pre-merge checks and finishing touches✅ Passed checks (3 passed)
✨ Finishing touches
🧪 Generate unit tests (beta)
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. Comment |
| 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"))?; |
There was a problem hiding this comment.
| 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.
There was a problem hiding this comment.
Actionable comments posted: 1
📜 Review details
Configuration used: Path: .coderabbit.yml
Review profile: CHILL
Plan: Pro
📒 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 (runcargo 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
PyListimport is required for the newadd_notemethod implementation and is correctly added in alphabetical order.
| #[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(()) | ||
| } |
There was a problem hiding this comment.
🧩 Analysis chain
Implementation looks solid, but consider more explicit error handling.
The add_note method correctly implements the expected behavior:
- Type safety via
PyStrRefparameter - 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.rsLength 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 keysOk(None)for missing keysErr(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.
Summary by CodeRabbit