Skip to content

Add set_attrs! macro for setting multiple attributes on an object#8034

Merged
youknowone merged 8 commits into
RustPython:mainfrom
ShaharNaveh:set-attrs-macro
Jun 9, 2026
Merged

Add set_attrs! macro for setting multiple attributes on an object#8034
youknowone merged 8 commits into
RustPython:mainfrom
ShaharNaveh:set-attrs-macro

Conversation

@ShaharNaveh

@ShaharNaveh ShaharNaveh commented Jun 3, 2026

Copy link
Copy Markdown
Contributor

Summary

Summary by CodeRabbit

  • Chores
    • Refactored internal attribute assignment to use batched operations across the VM and standard library, reducing repetition and improving consistency.
    • Minor formatting cleanup; no changes to public APIs, behaviors, or user-visible functionality.

@coderabbitai

coderabbitai Bot commented Jun 3, 2026

Copy link
Copy Markdown
Contributor

Wondering what really moved? Review this PR in Change Stack to inspect semantic changes, definitions, and references.

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yml

Review profile: CHILL

Plan: Pro

Run ID: d2d4ae87-4f70-41ca-8df4-ff1ca49dd229

📥 Commits

Reviewing files that changed from the base of the PR and between 98dc062 and ae7770b.

📒 Files selected for processing (1)
  • crates/vm/src/stdlib/_ctypes/simple.rs
🚧 Files skipped from review as they are similar to previous changes (1)
  • crates/vm/src/stdlib/_ctypes/simple.rs

📝 Walkthrough

Walkthrough

Adds an exported set_attrs! macro and replaces repeated set_attr calls with batched set_attrs! invocations in exception slot initialization, VM exception constructors, and ctypes byte-order wiring.

Changes

Macro Introduction and Cross-Crate Adoption

Layer / File(s) Summary
set_attrs! macro definition
crates/vm/src/protocol/object.rs
Exports set_attrs! with two forms (unwrap and error-propagating) that iterate key=>value pairs and call set_attr for each.
Exception type attribute initialization
crates/vm/src/exceptions.rs
Exception slot_init methods (PyAttributeError, PyUnicodeDecodeError, PyUnicodeEncodeError, PyUnicodeTranslateError) now use set_attrs!; types imports include the macro.
VM exception creation methods
crates/vm/src/vm/vm_new.rs
VM helpers that build exceptions (new_name_error, unicode error builders, new_syntax_error_maybe_incomplete, new_import_error) now use set_attrs! instead of chained set_attr calls.
Ctypes simple types byte-order attributes
crates/vm/src/stdlib/_ctypes/simple.rs
create_swapped_types consolidates endianness-related attribute assignments (__ctype_le__, __ctype_be__, _swappedbytes_) using set_attrs!; import block reformatted to include set_attrs and related types.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

  • RustPython/RustPython#7928: Edits to vm_new.rs's syntax-error construction path that touch similar exception-construction logic.

Suggested reviewers

  • youknowone

Poem

🐇 I nibble at boilerplate with cheer,

set_attrs! bundles fields near,
One call now sets many more,
Less tedium than days before,
Hopping onward, code feels clear.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 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 change: introducing a set_attrs! macro for setting multiple attributes on objects, which is clearly demonstrated across all modified files.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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.

.set_attr("__ctype_be__", type_ref.as_object().to_owned(), vm)?;
set_attrs!(
type_ref.as_object(), vm,
"__ctype_le__" => type_ref.as_object().to_owned(),

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.

I like this macro, but => is looking a bit awkward to me. is there other options that can show this is not a match flow?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

I think => was the clearest token, but if you have something else in mind I'd be happy tp change

@ShaharNaveh ShaharNaveh marked this pull request as ready for review June 4, 2026 06:11

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

🧹 Nitpick comments (2)
crates/vm/src/protocol/object.rs (1)

833-842: ⚡ Quick win

Consolidate duplicated macro branch logic.

Both set_attrs! arms repeat the same loop body and only differ in failure handling (unwrap vs ?). Please factor the differing behavior so the shared loop exists once.

As per coding guidelines, "When branches differ only in a value but share common logic, extract the differing value first, then call the common logic once to avoid duplicate code".

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@crates/vm/src/protocol/object.rs` around lines 833 - 842, The two arms of the
set_attrs! macro duplicate the same loop body but differ only by error handling
(one uses unwrap, the other uses ?); refactor by first selecting the
error-handling strategy (e.g., bind a local handler/closure or a flag like let
handle_err = |res| -> _ { res.unwrap() } or let handle_err = |res| -> _ { res?;
Ok(()) }) inside each match arm, then run the common loop once calling that
handler for each $obj.set_attr($key, $val, $vm) invocation; update the macro
arms so they differ only in the handler binding and then execute the shared loop
(referencing set_attrs!, set_attr, unwrap, and ? to locate the spots).
crates/vm/src/stdlib/_ctypes/simple.rs (1)

667-693: ⚡ Quick win

Collapse endian branches into one shared assignment path.

The if is_little_endian / else blocks duplicate the same set_attrs! calls and only differ in target values. Extract the two targets once, then invoke shared logic once.

♻️ Proposed refactor
-    if is_little_endian {
-        // Little-endian system: __ctype_le__ = self, __ctype_be__ = swapped
-        set_attrs!(
-            type_ref.as_object(), vm,
-            "__ctype_le__" => type_ref.as_object().to_owned(),
-            "__ctype_be__" => swapped_type.clone(),
-        );
-
-        set_attrs!(
-            swapped_type, vm,
-            "__ctype_le__" => type_ref.as_object().to_owned(),
-            "__ctype_be__" => swapped_type.clone(),
-        );
-    } else {
-        // Big-endian system: __ctype_be__ = self, __ctype_le__ = swapped
-        set_attrs!(
-            type_ref.as_object(), vm,
-            "__ctype_be__" => type_ref.as_object().to_owned(),
-            "__ctype_le__" => swapped_type.clone(),
-        );
-
-        set_attrs!(
-            swapped_type, vm,
-            "__ctype_be__" => type_ref.as_object().to_owned(),
-            "__ctype_le__" => swapped_type.clone(),
-        );
-    }
+    let type_obj = type_ref.as_object().to_owned();
+    let (ctype_le, ctype_be) = if is_little_endian {
+        (type_obj.clone(), swapped_type.clone())
+    } else {
+        (swapped_type.clone(), type_obj.clone())
+    };
+
+    set_attrs!(
+        type_ref.as_object(), vm,
+        "__ctype_le__" => ctype_le.clone(),
+        "__ctype_be__" => ctype_be.clone(),
+    );
+
+    set_attrs!(
+        swapped_type, vm,
+        "__ctype_le__" => ctype_le,
+        "__ctype_be__" => ctype_be,
+    );

As per coding guidelines, "When branches differ only in a value but share common logic, extract the differing value first, then call the common logic once to avoid duplicate code".

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@crates/vm/src/stdlib/_ctypes/simple.rs` around lines 667 - 693, The two
endian branches duplicate set_attrs! calls; compute the two attribute values
first based on is_little_endian (e.g. let ctype_le = if is_little_endian {
type_ref.as_object().to_owned() } else { swapped_type.clone() } and let ctype_be
= if is_little_endian { swapped_type.clone() } else {
type_ref.as_object().to_owned() }), then call set_attrs! once for
type_ref.as_object() and once for swapped_type using those computed ctype_le and
ctype_be variables; this removes the duplicated logic while keeping the same
semantics for type_ref, swapped_type, is_little_endian and the set_attrs! macro.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@crates/vm/src/protocol/object.rs`:
- Around line 833-842: The two arms of the set_attrs! macro duplicate the same
loop body but differ only by error handling (one uses unwrap, the other uses ?);
refactor by first selecting the error-handling strategy (e.g., bind a local
handler/closure or a flag like let handle_err = |res| -> _ { res.unwrap() } or
let handle_err = |res| -> _ { res?; Ok(()) }) inside each match arm, then run
the common loop once calling that handler for each $obj.set_attr($key, $val,
$vm) invocation; update the macro arms so they differ only in the handler
binding and then execute the shared loop (referencing set_attrs!, set_attr,
unwrap, and ? to locate the spots).

In `@crates/vm/src/stdlib/_ctypes/simple.rs`:
- Around line 667-693: The two endian branches duplicate set_attrs! calls;
compute the two attribute values first based on is_little_endian (e.g. let
ctype_le = if is_little_endian { type_ref.as_object().to_owned() } else {
swapped_type.clone() } and let ctype_be = if is_little_endian {
swapped_type.clone() } else { type_ref.as_object().to_owned() }), then call
set_attrs! once for type_ref.as_object() and once for swapped_type using those
computed ctype_le and ctype_be variables; this removes the duplicated logic
while keeping the same semantics for type_ref, swapped_type, is_little_endian
and the set_attrs! macro.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yml

Review profile: CHILL

Plan: Pro

Run ID: d14dd515-78ee-443c-99c1-bd2c0dd23f78

📥 Commits

Reviewing files that changed from the base of the PR and between f43ae46 and e8b834c.

📒 Files selected for processing (4)
  • crates/vm/src/exceptions.rs
  • crates/vm/src/protocol/object.rs
  • crates/vm/src/stdlib/_ctypes/simple.rs
  • crates/vm/src/vm/vm_new.rs

@youknowone youknowone merged commit fb422da into RustPython:main Jun 9, 2026
26 checks passed
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.

2 participants