Skip to content

Conversation

@JaeyoungAhn
Copy link
Contributor

@JaeyoungAhn JaeyoungAhn commented Mar 26, 2023

solved test case error for test_dictviews.py from fn rich_compare_bool in object.rs

Summary by CodeRabbit

  • Refactor
    • Extended Python object protocol implementation in the virtual machine with comprehensive support for object comparisons, attribute management, iteration, type checking, and subscripting operations.
    • Optimized equality and inequality comparisons with short-circuit evaluation for identical objects.

✏️ Tip: You can customize this high-level summary in your review settings.

@youknowone
Copy link
Member

i have no idea what's going on test_weakref

@youknowone youknowone added A-stdlib z-ca-2023 Tag to track contrubution-academy 2023 labels Mar 26, 2023
@fanninpm
Copy link
Contributor

i have no idea what's going on test_weakref

That's one of the flaky tests.

@DimitrisJim
Copy link
Member

That's one of the flaky tests.

Dunno if its flaky-ness here, triggering re-runs hasn't helped.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jan 4, 2026

📝 Walkthrough

Walkthrough

Introduces comprehensive Python object protocol implementation in the VM with optimized rich comparison short-circuiting for identical objects, alongside extensive new methods for attribute management, iteration, type checking, subscripting, comparison, and representation across PyObjectRef and PyObject.

Changes

Cohort / File(s) Summary
Comparison and Boolean Semantics
vm/src/protocol/object.rs
Added rich_compare(), rich_compare_bool() with identity-based short-circuit optimization for Eq/Ne operations, plus is_true(), not() for truthiness evaluation
Attribute Protocol
vm/src/protocol/object.rs
Implemented full attribute management via get_attr(), set_attr(), del_attr(), has_attr(), get_attr_inner(), call_set_attr(), generic_getattr(), generic_getattr_opt() with descriptor protocol and fallback handling
Iteration and Length
vm/src/protocol/object.rs
Added get_iter(), get_aiter() for iteration, length(), length_opt(), length_hint() for size queries, and dir() for attribute enumeration
Subscripting and Containment
vm/src/protocol/object.rs
Introduced get_item(), set_item(), del_item() for mapping/sequence protocol operations
Type and Instance Checking
vm/src/protocol/object.rs
Implemented obj_type(), type_check() for type introspection and subclass/instance validation
Representation and Conversion
vm/src/protocol/object.rs
Added repr(), ascii(), bytes() for object stringification and data conversion

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

Poem

🐰 A protocol so grand, with objects at hand,
Comparisons swift when they're the same,
Attributes found, iteration around,
The VM's now richer in every way! ✨

Pre-merge checks and finishing touches

❌ Failed checks (2 warnings)
Check name Status Explanation Resolution
Title check ⚠️ Warning The title mentions fixing a test error in test_dictviews.py from object.rs, which aligns with the small optimization in rich_compare_bool but significantly underrepresents the extensive object protocol implementation comprising the bulk of changes. Update the title to reflect the primary change: comprehensive Python object protocol implementation with rich comparisons, attribute management, iteration, and error handling across PyObjectRef and PyObject.
Docstring Coverage ⚠️ Warning Docstring coverage is 37.84% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (1 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
✨ 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

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

Copy link
Contributor

@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: 3

📜 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 e1b22f1 and 0965d94.

⛔ Files ignored due to path filters (1)
  • Lib/test/test_dictviews.py is excluded by !Lib/**
📒 Files selected for processing (2)
  • crates/vm/src/protocol/object.rs
  • vm/src/protocol/object.rs
🧰 Additional context used
📓 Path-based instructions (1)
**/*.rs

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

**/*.rs: Follow the default rustfmt code style by running cargo fmt to format Rust code
Always run clippy to lint code (cargo clippy) before completing tasks and fix any warnings or lints introduced by changes
Follow Rust best practices for error handling and memory management
Use the macro system (pyclass, pymodule, pyfunction, etc.) when implementing Python functionality in Rust

Files:

  • crates/vm/src/protocol/object.rs
  • vm/src/protocol/object.rs
🧠 Learnings (1)
📚 Learning: 2025-12-27T14:03:49.034Z
Learnt from: CR
Repo: RustPython/RustPython PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-12-27T14:03:49.034Z
Learning: Applies to **/*.rs : Use the macro system (`pyclass`, `pymodule`, `pyfunction`, etc.) when implementing Python functionality in Rust

Applied to files:

  • vm/src/protocol/object.rs
🧬 Code graph analysis (1)
crates/vm/src/protocol/object.rs (9)
crates/stdlib/src/array.rs (2)
  • other (1061-1061)
  • other (1080-1080)
crates/vm/src/builtins/memory.rs (1)
  • other (332-332)
crates/vm/src/builtins/tuple.rs (1)
  • other (271-271)
crates/vm/src/stdlib/collections.rs (1)
  • other (351-351)
crates/vm/src/builtins/str.rs (1)
  • other (545-545)
crates/vm/src/builtins/int.rs (3)
  • other (302-303)
  • other (313-313)
  • other (582-583)
crates/vm/src/builtins/complex.rs (1)
  • other (306-306)
crates/vm/src/builtins/float.rs (2)
  • other (348-348)
  • other (352-352)
crates/vm/src/types/structseq.rs (1)
  • other (375-375)
⏰ 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: Run snippets and cpython tests (ubuntu-latest)
  • GitHub Check: Run snippets and cpython tests (windows-latest)
  • GitHub Check: Run rust tests (macos-latest)
  • GitHub Check: Run rust tests (windows-latest)
  • GitHub Check: Check the WASM package and demo
  • GitHub Check: Run snippets and cpython tests (macos-latest)
  • GitHub Check: Run snippets and cpython tests on wasm-wasi
  • GitHub Check: Run tests under miri
  • GitHub Check: Check Rust code with clippy
  • GitHub Check: Run rust tests (ubuntu-latest)
  • GitHub Check: Ensure compilation on various targets
🔇 Additional comments (2)
crates/vm/src/protocol/object.rs (1)

335-346: Short-circuit optimization for identity-based equality looks correct.

This optimization aligns with CPython's PyObject_RichCompareBool behavior where identity implies equality. When self.is(other):

  • Eq returns true immediately
  • Ne returns false immediately

For other comparison operators (Lt, Le, Gt, Ge), the full comparison logic correctly proceeds since identity doesn't determine ordering.

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

336-347: Short-circuit optimization for identity-based equality is correct.

This optimization matches CPython's PyObject_RichCompareBool behavior, correctly short-circuiting Eq/Ne comparisons for identical objects while allowing other comparison operators to proceed through the full comparison logic.

Comment on lines +94 to +101
// PyObject *PyObject_GetAIter(PyObject *o)
pub fn get_aiter(&self, vm: &VirtualMachine) -> PyResult {
if self.payload_is::<PyAsyncGen>() {
vm.call_special_method(self, identifier!(vm, __aiter__), ())
} else {
Err(vm.new_type_error("wrong argument type".to_owned()))
}
}
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

get_aiter implementation is too restrictive.

This only works for PyAsyncGen objects, but any async iterable with __aiter__ should be supported. Compare with the other file's implementation which properly checks for __aiter__, validates the result has __anext__, and provides meaningful error messages.

The current error message "wrong argument type" is also non-specific compared to Python's expected "'X' object is not an async iterable".

🔎 Suggested implementation pattern
 pub fn get_aiter(&self, vm: &VirtualMachine) -> PyResult {
-    if self.payload_is::<PyAsyncGen>() {
-        vm.call_special_method(self, identifier!(vm, __aiter__), ())
-    } else {
-        Err(vm.new_type_error("wrong argument type".to_owned()))
+    // Check if object has __aiter__ method
+    let aiter_method = self.class().get_attr(identifier!(vm, __aiter__));
+    if aiter_method.is_none() {
+        return Err(vm.new_type_error(format!(
+            "'{}' object is not an async iterable",
+            self.class().name()
+        )));
     }
+    
+    let iterator = vm.call_special_method(self, identifier!(vm, __aiter__), ())?;
+    
+    // Check that the result has __anext__
+    if !iterator.class().has_attr(identifier!(vm, __anext__)) {
+        return Err(vm.new_type_error(format!(
+            "'{}' object is not an async iterator",
+            iterator.class().name()
+        )));
+    }
+    
+    Ok(iterator)
 }

Comment on lines +103 to +105
pub fn has_attr<'a>(&self, attr_name: impl AsPyStr<'a>, vm: &VirtualMachine) -> PyResult<bool> {
self.get_attr(attr_name, vm).map(|o| !vm.is_none(&o))
}
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

has_attr implementation has incorrect semantics.

If an attribute exists but its value is None, hasattr will still return True. However, this implementation returns false when the attribute value is Python's None object.

Additionally, if get_attr raises an AttributeError for a non-existent attribute, this propagates the error instead of returning false. Python's hasattr catches AttributeError and returns false.

🔎 Proposed fix
 pub fn has_attr<'a>(&self, attr_name: impl AsPyStr<'a>, vm: &VirtualMachine) -> PyResult<bool> {
-    self.get_attr(attr_name, vm).map(|o| !vm.is_none(&o))
+    match self.get_attr(attr_name, vm) {
+        Ok(_) => Ok(true),
+        Err(e) if e.class().is(vm.ctx.exceptions.attribute_error) => Ok(false),
+        Err(e) => Err(e),
+    }
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
pub fn has_attr<'a>(&self, attr_name: impl AsPyStr<'a>, vm: &VirtualMachine) -> PyResult<bool> {
self.get_attr(attr_name, vm).map(|o| !vm.is_none(&o))
}
pub fn has_attr<'a>(&self, attr_name: impl AsPyStr<'a>, vm: &VirtualMachine) -> PyResult<bool> {
match self.get_attr(attr_name, vm) {
Ok(_) => Ok(true),
Err(e) if e.class().is(vm.ctx.exceptions.attribute_error) => Ok(false),
Err(e) => Err(e),
}
}
🤖 Prompt for AI Agents
In vm/src/protocol/object.rs around lines 103-105, has_attr currently returns
false for attributes whose value is Python None and lets AttributeError
propagate; change it so that it returns Ok(true) whenever get_attr succeeds
(regardless of the attribute value), and only returns Ok(false) when get_attr
fails with an AttributeError; any other error should continue to propagate.
Implement this by calling self.get_attr(...), mapping an Ok(_) to Ok(true), and
matching Err(err) to detect AttributeError (returning Ok(false)) versus
re-raising other errors.

Comment on lines +423 to +436
_ => {
if let Some(i) = (0..n).next() {
let check = vm.with_recursion("in abstract_issubclass", || {
tuple.fast_getitem(i).abstract_issubclass(cls, vm)
})?;
if check {
return Ok(true);
}
}
}
}

return Ok(false);
}
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🔴 Critical

Bug: Multiple inheritance case only checks the first base class.

The expression (0..n).next() always returns Some(0), so this only checks the first base at index 0. After the match block, it returns Ok(false) without checking the remaining bases.

For example, if a class inherits from (A, B) where B is the target class, this would incorrectly return false because it only checks A.

🔎 Proposed fix
             _ => {
-                if let Some(i) = (0..n).next() {
+                for i in 0..n {
                     let check = vm.with_recursion("in abstract_issubclass", || {
                         tuple.fast_getitem(i).abstract_issubclass(cls, vm)
                     })?;
                     if check {
                         return Ok(true);
                     }
                 }
+                return Ok(false);
             }
         }
-
-        return Ok(false);
     }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
_ => {
if let Some(i) = (0..n).next() {
let check = vm.with_recursion("in abstract_issubclass", || {
tuple.fast_getitem(i).abstract_issubclass(cls, vm)
})?;
if check {
return Ok(true);
}
}
}
}
return Ok(false);
}
_ => {
for i in 0..n {
let check = vm.with_recursion("in abstract_issubclass", || {
tuple.fast_getitem(i).abstract_issubclass(cls, vm)
})?;
if check {
return Ok(true);
}
}
return Ok(false);
}
}
}
🤖 Prompt for AI Agents
In vm/src/protocol/object.rs around lines 423 to 436, the code uses
(0..n).next() which always yields index 0 and thus only checks the first base
class; change this to iterate over all base indices (e.g., for i in 0..n or
while let Some(i) = iter.next() over the full range) and perform the
vm.with_recursion check for each base, returning Ok(true) as soon as any check
succeeds and only returning Ok(false) after all bases have been checked.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

A-stdlib z-ca-2023 Tag to track contrubution-academy 2023

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants