Skip to content

Fix dict unpack #5809

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 4 commits into from
Jun 22, 2025
Merged

Fix dict unpack #5809

merged 4 commits into from
Jun 22, 2025

Conversation

youknowone
Copy link
Member

@youknowone youknowone commented Jun 21, 2025

fix #5645

Summary by CodeRabbit

  • Bug Fixes

    • Improved handling of dictionary unpacking and keyword arguments to support any mapping-like object, with clearer error messages for non-mapping objects and non-string keys.
    • Updated tests to ensure correct behavior when unpacking various types into dictionaries, including proper error handling and order preservation with OrderedDict.
  • Documentation

    • Clarified coding guidelines regarding where Python code should be edited versus Rust code.
  • Tests

    • Added new tests for dictionary unpacking and keyword argument order preservation.
    • Updated an existing test to reflect that keyword argument order is now correctly handled and expected to pass.

@youknowone youknowone requested a review from Copilot June 21, 2025 14:54
Copy link

coderabbitai bot commented Jun 21, 2025

Walkthrough

The updates improve Python dictionary unpacking and keyword argument handling in the RustPython VM. Dictionary unpacking now supports any mapping with a keys method, not just dict. Tests are added and updated to verify correct error handling and order preservation. Documentation is updated to clarify the preferred workflow for Python code changes.

Changes

File(s) Change Summary
.github/copilot-instructions.md Added guideline: prefer fixing Python code bugs via Rust code changes, not direct Python edits.
Lib/test/test_call.py Removed expected failure decorator from test_kwargs_order, so the test is now expected to pass.
extra_tests/snippets/builtin_dict.py Added tests for dictionary unpacking error cases and order preservation with mappings.
vm/src/frame.rs Generalized dictionary unpacking and kwargs handling to accept any mapping with a keys method; added error handling for non-mappings and non-string keys.

Sequence Diagram(s)

sequenceDiagram
    participant PythonUser
    participant PythonVM
    participant MappingObject

    PythonUser->>PythonVM: Call function with **kwargs or dict unpacking
    PythonVM->>MappingObject: Check for keys() method
    alt keys() exists
        PythonVM->>MappingObject: Call keys()
        MappingObject-->>PythonVM: Return keys
        loop For each key
            PythonVM->>MappingObject: get_item(key)
            alt key is string
                PythonVM->>PythonVM: Add to kwargs/dict
            else key is not string
                PythonVM->>PythonUser: Raise TypeError (key not string)
            end
        end
    else keys() missing
        PythonVM->>PythonUser: Raise TypeError (not a mapping)
    end
Loading

Assessment against linked issues

Objective Addressed Explanation
Support ** dict unpacking with arbitrary mappings, not just dicts (#5645)
Raise TypeError when unpacking non-mapping objects (#5645)
Raise TypeError when keys are not strings in unpacked mappings (#5645)
Preserve order of keyword arguments when unpacking OrderedDict (#5645)

Assessment against linked issues: Out-of-scope changes

No out-of-scope changes detected.

Poem

In the warren of code, a change hops along,
Now mappings with keys can join Python’s song.
Dicts, OrderedDicts, all hop in the queue,
If you lack “keys”, we’ll say “no can do!”
Tests now ensure, with a bunny’s delight,
That order and errors are handled just right.
🐇✨


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between aed3890 and d973e6d.

📒 Files selected for processing (2)
  • extra_tests/snippets/builtin_dict.py (1 hunks)
  • vm/src/frame.rs (5 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • extra_tests/snippets/builtin_dict.py
⏰ Context from checks skipped due to timeout of 90000ms (11)
  • GitHub Check: Run snippets and cpython tests (windows-latest)
  • GitHub Check: Run snippets and cpython tests (macos-latest)
  • GitHub Check: Run tests under miri
  • GitHub Check: Run snippets and cpython tests (ubuntu-latest)
  • GitHub Check: Run snippets and cpython tests on wasm-wasi
  • GitHub Check: Check the WASM package and demo
  • GitHub Check: Check Rust code with rustfmt and clippy
  • GitHub Check: Run rust tests (windows-latest)
  • GitHub Check: Run rust tests (ubuntu-latest)
  • GitHub Check: Run rust tests (macos-latest)
  • GitHub Check: Ensure compilation on various targets
🔇 Additional comments (1)
vm/src/frame.rs (1)

799-810: LGTM! Excellent generalization of dictionary unpacking.

The change from exact dict checking to mapping protocol detection correctly enables dictionary unpacking to work with any mapping object (OrderedDict, UserDict, etc.), not just exact dicts. The error handling is appropriate and follows Python's mapping protocol standards.

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

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

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

@Copilot Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull Request Overview

This PR fixes the dictionary unpacking behavior to ensure that only mapping objects (i.e., those providing the keys() method) are accepted, and it adjusts kwargs collection accordingly. Key changes include:

  • Adding a mapping protocol check before merging unpacked dictionaries.
  • Refactoring kwargs extraction to use the keys() method in place of a direct dict downcast.
  • Updating tests to verify error messages and order preservation, and clarifying documentation about modifying Python code.

Reviewed Changes

Copilot reviewed 4 out of 4 changed files in this pull request and generated 2 comments.

File Description
vm/src/frame.rs Fixes to dict unpacking and kwargs collection to enforce mapping protocol via keys() method.
extra_tests/snippets/builtin_dict.py New tests for dict unpacking with non-mapping objects and order preservation in OrderedDict.
Lib/test/test_call.py Removal of an expected failure marker for kwargs order, reflecting the implementation fix.
.github/copilot-instructions.md Updated note to discourage editing Python code for bug fixes.

vm/src/frame.rs Outdated
Comment on lines 1543 to 1556
// Use keys() method for all mapping objects to preserve order
let Some(keys_method) = vm.get_method(obj.clone(), vm.ctx.intern_str("keys")) else {
return Err(
vm.new_type_error(format!("'{}' object is not a mapping", obj.class().name()))
);
};

let keys = keys_method?.call((), vm)?.get_iter(vm)?;
while let PyIterReturn::Return(key) = keys.next(vm)? {
// Check for keyword argument restrictions
if key.downcast_ref::<PyStr>().is_none() {
return Err(vm.new_type_error("keywords must be strings".to_owned()));
}

Copy link
Preview

Copilot AI Jun 21, 2025

Choose a reason for hiding this comment

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

Consider abstracting the common pattern for retrieving mapping keys (via the keys() method) into a helper function to reduce code duplication and enhance maintainability.

Copilot uses AI. Check for mistakes.

vm/src/frame.rs Outdated
let key = key

// Use keys() method for all mapping objects to preserve order
let Some(keys_method) = vm.get_method(kw_obj.clone(), vm.ctx.intern_str("keys")) else {
Copy link
Preview

Copilot AI Jun 21, 2025

Choose a reason for hiding this comment

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

Consider refactoring the repeated mapping keys retrieval logic (used both in dict unpacking and kwargs extraction) into a shared utility function for better code reuse.

Copilot uses AI. Check for mistakes.

@youknowone youknowone merged commit efc6b5d into RustPython:main Jun 22, 2025
12 checks passed
@youknowone youknowone deleted the fix-dict-unpack branch June 22, 2025 00:08
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.

** dict unpacking is buggy
1 participant