Skip to content

Fix __dict__ getset type #6010

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 2 commits into from
Jul 21, 2025
Merged

Fix __dict__ getset type #6010

merged 2 commits into from
Jul 21, 2025

Conversation

youknowone
Copy link
Member

@youknowone youknowone commented Jul 20, 2025

Summary by CodeRabbit

  • Refactor
    • Improved the handling of the __dict__ attribute on types to better align with standard Python behavior, enhancing internal consistency without affecting user-facing features.

Copy link
Contributor

coderabbitai bot commented Jul 20, 2025

Walkthrough

The change refactors the process of adding the __dict__ descriptor during Python type object creation. Instead of inserting the descriptor before the type is created, it now adds it directly to the type's attributes after initialization, using a different method and maintaining the same condition for insertion. Additionally, the logic for locating the base type with a dictionary and retrieving the __dict__ descriptor is restructured with new helper functions, improving alignment with CPython's approach.

Changes

File(s) Change Summary
vm/src/builtins/type.rs Moved __dict__ descriptor insertion to after type object creation with unsafe attribute insertion; replaced find_base_dict_descr with get_builtin_base_with_dict and get_dict_descriptor; rewrote subtype_get_dict and subtype_set_dict to use new helper functions and updated error handling.

Sequence Diagram(s)

sequenceDiagram
    participant Caller
    participant PyTypeConstructor
    participant TypeObject
    participant BaseTypeWithDict
    participant DictDescriptor

    Caller->>PyTypeConstructor: Create new type
    PyTypeConstructor->>TypeObject: Initialize type object
    alt If base is not type
        PyTypeConstructor->>TypeObject: Insert __dict__ descriptor (post-creation)
    end
    Caller->>TypeObject: Access __dict__
    TypeObject->>BaseTypeWithDict: Find builtin base with dict
    BaseTypeWithDict->>DictDescriptor: Lookup __dict__ descriptor
    DictDescriptor->>TypeObject: Get or set __dict__ value
Loading

Estimated code review effort

2 (60 minutes)

Possibly related PRs

  • type.__dict__ #5957: Adds tests and minor constructor logic changes related to __dict__ presence in type and subclasses, closely related to managing the __dict__ descriptor in PyType.

Poem

In the warren of code, a change takes flight,
The __dict__ now lands after type’s first light.
No more before—now after, it’s true,
With careful precision, the rabbits renew.
Hopping through Rust, descriptors in tow,
The type’s little secrets continue to grow! 🐇


📜 Recent review details

Configuration used: .coderabbit.yml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 5717700 and f9557a0.

📒 Files selected for processing (1)
  • vm/src/builtins/type.rs (5 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • vm/src/builtins/type.rs
⏰ 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). (10)
  • GitHub Check: Run snippets and cpython tests on wasm-wasi
  • GitHub Check: Check the WASM package and demo
  • GitHub Check: Run rust tests (windows-latest)
  • GitHub Check: Run rust tests (macos-latest)
  • GitHub Check: Run rust tests (ubuntu-latest)
  • GitHub Check: Ensure compilation on various targets
  • GitHub Check: Run snippets and cpython tests (macos-latest)
  • GitHub Check: Run snippets and cpython tests (ubuntu-latest)
  • GitHub Check: Run snippets and cpython tests (windows-latest)
  • GitHub Check: Check Rust code with rustfmt and clippy
✨ 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
🪧 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.

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
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: 0

🧹 Nitpick comments (1)
vm/src/builtins/type.rs (1)

1476-1529: Excellent refactoring that improves CPython alignment and code organization.

The refactored subtype_get_dict and subtype_set_dict functions are much cleaner:

✅ Proper use of the new helper functions for separation of concerns
✅ Better alignment with CPython's implementation approach
✅ Consistent error handling and messaging
✅ Appropriate fallback to generic object dict operations
✅ Clear comments indicating CPython equivalence

Consider extracting the repeated error message pattern into a helper function to reduce duplication:

fn dict_descriptor_error(obj: &PyObject, vm: &VirtualMachine) -> PyBaseExceptionRef {
    vm.new_type_error(format!(
        "this __dict__ descriptor does not support '{}' objects",
        obj.class().name()
    ))
}

This would eliminate the duplicated error message on lines 1484-1487, 1491-1493, 1513-1515, and 1520-1522.

📜 Review details

Configuration used: .coderabbit.yml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between d56cd41 and 3ab63ef.

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

Instructions used from:

Sources:
📄 CodeRabbit Inference Engine

  • .github/copilot-instructions.md
🧠 Learnings (1)
vm/src/builtins/type.rs (1)
Learnt from: CR
PR: RustPython/RustPython#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-07-19T03:16:56.511Z
Learning: Applies to **/*.rs : Use the macro system (`pyclass`, `pymodule`, `pyfunction`, etc.) when implementing Python functionality in Rust
🔇 Additional comments (2)
vm/src/builtins/type.rs (2)

1125-1142: Good improvement to dict descriptor handling, but clarify unsafe usage.

The move from pre-creation to post-creation insertion of the __dict__ descriptor is a solid improvement that ensures the descriptor has the correct __objclass__ reference. The logic and conditions look correct.

However, the unsafe block needs justification:

  • Why is unsafe necessary here when other attribute insertions don't require it?
  • The comment explains the "what" but not the "why" of the unsafe usage.

Could you clarify why the unsafe block is required for this specific descriptor creation when other attribute insertions in the same function don't use unsafe?


1449-1474: Well-implemented helper functions that align with CPython.

Both get_builtin_base_with_dict and get_dict_descriptor are cleanly implemented:

✅ Clear CPython equivalence documentation
✅ Proper flag checking (HAS_DICT, HEAPTYPE)
✅ Correct handling of the type special case
✅ Appropriate use of Option return types
✅ Good function naming that matches CPython conventions

The base chain iteration logic is correct and the descriptor lookup using lookup_ref properly mimics CPython's _PyType_Lookup.

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: 0

🧹 Nitpick comments (1)
vm/src/builtins/type.rs (1)

1144-1162: Document the unsafe block and verify its safety.

The post-creation __dict__ descriptor insertion logic is sound and addresses the timing issue mentioned in the AI summary. However, the unsafe block needs proper documentation.

Add a safety comment explaining why the unsafe block is necessary:

+                // SAFETY: We're creating a getset descriptor with static function pointers
+                // (subtype_get_dict, subtype_set_dict) and the type reference is valid
+                // since we just created it above.
                 unsafe {
                     let descriptor =
                         vm.ctx
                             .new_getset("__dict__", &typ, subtype_get_dict, subtype_set_dict);
                     typ.attributes.write().insert(__dict__, descriptor.into());
                 }

The logic correctly prevents type subclasses from getting duplicate __dict__ descriptors and ensures the descriptor is only added when needed.

📜 Review details

Configuration used: .coderabbit.yml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 3ab63ef and 6930d0c.

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

Instructions used from:

Sources:
📄 CodeRabbit Inference Engine

  • .github/copilot-instructions.md
🧠 Learnings (1)
vm/src/builtins/type.rs (1)

Learnt from: CR
PR: RustPython/RustPython#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-07-19T03:16:56.511Z
Learning: Applies to **/*.rs : Use the macro system (pyclass, pymodule, pyfunction, etc.) when implementing Python functionality in Rust

🧬 Code Graph Analysis (1)
vm/src/builtins/type.rs (2)
vm/src/builtins/tuple.rs (1)
  • new_ref_typed (234-242)
vm/src/builtins/object.rs (2)
  • object_get_dict (496-499)
  • object_set_dict (500-503)
🔇 Additional comments (3)
vm/src/builtins/type.rs (3)

1022-1076: LGTM: Correct slots and dict interaction logic.

The enhanced slots processing correctly implements Python's semantics:

  • Detects __dict__ in __slots__ and sets the add_dict flag
  • Filters out __dict__ from the actual slots list (since it's handled specially)
  • Sets HAS_DICT and MANAGED_DICT flags when no slots are defined OR when __dict__ is explicitly in slots

This aligns well with CPython's behavior where __dict__ in __slots__ is treated as a special case.


1468-1548: LGTM: Well-structured helper functions that improve CPython alignment.

The new helper functions are well-designed and improve the codebase:

  1. get_builtin_base_with_dict: Correctly traverses the base chain looking for builtin types with dictionary support, with proper handling of the special case for type itself.

  2. get_dict_descriptor: Clean abstraction that uses lookup_ref to match CPython's _PyType_LookupRef behavior.

  3. subtype_get_dict/subtype_set_dict: The rewrite improves error handling and follows CPython's logic more closely. The fallback to object::object_get_dict/object::object_set_dict is appropriate.

The separation of concerns makes the code more maintainable and easier to understand.


1022-1162: Verify __dict__ descriptor tests continue to pass

I ran searches for existing __dict__–related tests and didn’t find any Rust-side checks or direct Python tests exercising post-creation descriptor timing. To ensure this refactoring hasn’t regressed __dict__ behavior, please:

  • Run the Python test suite, focusing on files that reference __dict__ in extra_tests/snippets:
    • extra_tests/snippets/builtin_object.py
    • extra_tests/snippets/builtin_mappingproxy.py
    • extra_tests/snippets/builtin_type.py
    • extra_tests/snippets/builtins_module.py
    • extra_tests/snippets/builtin_exceptions.py
  • Add or update tests that explicitly access an instance’s __dict__ before and after defining __slots__ to confirm __objclass__ is correctly set.
  • Search for any Rust tests or code paths that inspect __objclass__ on descriptors and add coverage if missing.

Without explicit coverage, timing changes may slip through. Please verify these tests still pass (or add new ones) to confirm no regressions around __dict__ descriptor behavior.

@youknowone youknowone merged commit a1ee7f5 into RustPython:main Jul 21, 2025
12 checks passed
@youknowone youknowone deleted the dict-getset branch July 21, 2025 07:13
@coderabbitai coderabbitai bot mentioned this pull request Aug 8, 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.

1 participant