Skip to content

heaptype __qualname__ #5848

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 1 commit into from
Jun 27, 2025
Merged

heaptype __qualname__ #5848

merged 1 commit into from
Jun 27, 2025

Conversation

youknowone
Copy link
Member

@youknowone youknowone commented Jun 27, 2025

Summary by CodeRabbit

  • New Features

    • Improved dictionary behavior to allow popping a key and returning its value if present, or None if absent, without raising an error.
    • Enhanced support for Python type qualified names, aligning behavior more closely with standard Python.
  • Refactor

    • Unified and clarified dictionary removal methods, now returning the removed value when applicable.
  • Tests

    • Updated test cases by removing expected failure markers to run as normal tests.

Copy link

coderabbitai bot commented Jun 27, 2025

Walkthrough

This update introduces a new pop_item method to the Python dictionary implementation, refactors dictionary removal methods for clarity and better return values, and moves type __qualname__ storage to a dedicated field in heap types. Additionally, it removes expected failure decorators from two typing and descriptor tests, enabling them for regular execution.

Changes

File(s) Change Summary
Lib/test/test_typing.py Removed @unittest.expectedFailure decorators and related comments from two test methods.
Lib/test/test_descr.py Removed @unittest.expectedFailure decorators from two test methods, keeping TODO comments.
vm/src/builtins/dict.rs Added pop_item method to PyDict for popping keys without raising errors.
vm/src/dict_inner.rs Refactored and renamed dictionary removal methods to return removed values; unified and clarified API.
vm/src/builtins/type.rs Moved __qualname__ storage to a dedicated field in heap types; updated getter/setter and type creation logic.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant PyDict
    participant DictInner
    participant VM

    User->>PyDict: pop_item(key, vm)
    alt Exact dict
        PyDict->>DictInner: remove_if_exists(key, vm)
        DictInner-->>PyDict: Option<value>
        PyDict-->>User: Option<value>
    else Subclass/proxy
        PyDict->>PyDict: get(key, vm)
        PyDict->>PyDict: delitem(key, vm)
        PyDict-->>User: Option<value>
    end
Loading
sequenceDiagram
    participant User
    participant PyType
    participant HeapTypeExt

    User->>PyType: set __qualname__(value)
    PyType->>HeapTypeExt: Store value in qualname field

    User->>PyType: get __qualname__()
    PyType->>HeapTypeExt: Read qualname field
    HeapTypeExt-->>PyType: qualname or fallback to name
    PyType-->>User: qualname
Loading

Possibly related PRs

  • RustPython/RustPython#5844: Removes @unittest.expectedFailure decorators from typing protocol tests, directly related to enabling similar tests.
  • RustPython/RustPython#5837: Removes expected failure decorators from a broader set of typing tests in the same file, sharing scope and file.
  • RustPython/RustPython#5840: Cleans up expected failure markers in typing tests, affecting the same test file and decorator usage.

Suggested reviewers

  • arihant2math

Poem

In the warren of code, a new pop appears,
Dicts now return what they quietly clear.
Qualnames find homes, snug in their heap,
While old test failures no longer creep.
With carrots and keys, this bunny delights—
Hopping through changes on bright, starry nights!
🥕


📜 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 fe81249 and efb3d43.

📒 Files selected for processing (5)
  • Lib/test/test_descr.py (1 hunks)
  • Lib/test/test_typing.py (0 hunks)
  • vm/src/builtins/dict.rs (1 hunks)
  • vm/src/builtins/type.rs (7 hunks)
  • vm/src/dict_inner.rs (2 hunks)
💤 Files with no reviewable changes (1)
  • Lib/test/test_typing.py
🚧 Files skipped from review as they are similar to previous changes (3)
  • vm/src/builtins/dict.rs
  • vm/src/dict_inner.rs
  • vm/src/builtins/type.rs
🧰 Additional context used
📓 Path-based instructions (2)
`Lib/**/*`: Files in the Lib/ directory (Python standard library copied from CPy...

Lib/**/*: Files in the Lib/ directory (Python standard library copied from CPython) should be edited very conservatively; modifications should be minimal and only to work around RustPython limitations.

📄 Source: CodeRabbit Inference Engine (.github/copilot-instructions.md)

List of files the instruction was applied to:

  • Lib/test/test_descr.py
`Lib/test/**/*`: Tests in Lib/test often use markers such as '# TODO: RUSTPYTHON...

Lib/test/**/*: Tests in Lib/test often use markers such as '# TODO: RUSTPYTHON', 'unittest.skip("TODO: RustPython ")', or 'unittest.expectedFailure' with a '# TODO: RUSTPYTHON ' comment when modifications are made.
NEVER comment out or delete any test code lines except for removing '@unittest.expectedFailure' decorators and upper TODO comments.
NEVER modify test assertions, test logic, or test data in Lib/test files.
The only acceptable modifications to test files are: (1) removing '@unittest.expectedFailure' decorators and the upper TODO comments when tests actually pass, (2) adding '@unittest.expectedFailure' decorators when tests cannot be fixed.
When a test cannot pass due to missing language features, keep it as expectedFailure and document the reason.

📄 Source: CodeRabbit Inference Engine (.github/copilot-instructions.md)

List of files the instruction was applied to:

  • Lib/test/test_descr.py
🧠 Learnings (1)
Lib/test/test_descr.py (1)

undefined

<retrieved_learning>
Learnt from: CR
PR: RustPython/RustPython#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-06-26T12:52:11.109Z
Learning: When a test fails due to unsupported Python syntax or features, keep the test as '@unittest.expectedFailure' and document the reason, rather than modifying the test logic or data.
</retrieved_learning>

🧬 Code Graph Analysis (1)
Lib/test/test_descr.py (1)
Lib/unittest/case.py (1)
  • expectedFailure (183-185)
⏰ Context from checks skipped due to timeout of 90000ms (10)
  • 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 snippets and cpython tests (windows-latest)
  • GitHub Check: Run snippets and cpython tests (macos-latest)
  • GitHub Check: Run rust tests (macos-latest)
  • GitHub Check: Run rust tests (windows-latest)
  • GitHub Check: Run rust tests (ubuntu-latest)
  • GitHub Check: Ensure compilation on various targets
🔇 Additional comments (1)
Lib/test/test_descr.py (1)

5127-5131: Verify the actual changes made to expectedFailure decorators.

There's a discrepancy between the AI summary and the observed changes. The summary states that @unittest.expectedFailure decorators were removed from test_iter_values to enable normal test execution, but I can see the decorator is present in the code with change markers (~).

According to the coding guidelines, modifications to test files should only involve:

  1. Removing @unittest.expectedFailure decorators when tests actually pass
  2. Adding @unittest.expectedFailure decorators when tests cannot be fixed

Please clarify whether:

  • The decorator is being added to this test (contrary to the summary)
  • The decorator is being removed but the diff format is confusing
  • There are other modifications to the decorator or TODO comment

If tests are now passing due to RustPython VM improvements, removing the expectedFailure decorator would be appropriate. If tests are still failing, the decorator should remain.

#!/bin/bash
# Check the git diff to see the actual changes made to expectedFailure decorators
git log --oneline -1 --name-only
git show --name-only HEAD
rg -A5 -B5 "test_iter_values|test_bound_method_repr" Lib/test/test_descr.py
✨ 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

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

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

869-875: Consider using expect instead of silent fallback.

Since __qualname__ is already validated to be a string at lines 222-229, the and_then with downcast_ref silently ignoring non-string values seems unnecessary. Consider using expect to make the invariant clear.

 let qualname = dict
     .pop_item(identifier!(vm, __qualname__).as_object(), vm)?
-    .and_then(|obj| obj.downcast_ref::<PyStr>().map(|s| s.to_owned()))
-    .or_else(|| {
-        // If __qualname__ is not provided, we can use the name as default
-        Some(name.clone())
-    });
+    .map(|obj| obj.downcast::<PyStr>().expect("__qualname__ already validated"))
+    .unwrap_or_else(|| name.clone());
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between f0c7cb2 and fe81249.

📒 Files selected for processing (4)
  • Lib/test/test_typing.py (0 hunks)
  • vm/src/builtins/dict.rs (1 hunks)
  • vm/src/builtins/type.rs (6 hunks)
  • vm/src/dict_inner.rs (2 hunks)
💤 Files with no reviewable changes (1)
  • Lib/test/test_typing.py
🧰 Additional context used
🧬 Code Graph Analysis (1)
vm/src/builtins/type.rs (5)
vm/src/builtins/function.rs (7)
  • new (58-103)
  • new (722-724)
  • new (846-850)
  • __qualname__ (487-489)
  • __qualname__ (772-791)
  • value (495-495)
  • obj (449-449)
vm/src/builtins/descriptor.rs (4)
  • new (34-44)
  • __qualname__ (117-119)
  • __qualname__ (252-262)
  • qualname (235-235)
vm/src/protocol/object.rs (1)
  • s (360-360)
vm/src/builtins/builtin_func.rs (2)
  • __qualname__ (87-107)
  • __qualname__ (155-160)
vm/src/builtins/module.rs (2)
  • name (118-124)
  • name (123-123)
⏰ Context from checks skipped due to timeout of 90000ms (10)
  • GitHub Check: Run snippets and cpython tests on wasm-wasi
  • GitHub Check: Run snippets and cpython tests (macos-latest)
  • GitHub Check: Check the WASM package and demo
  • GitHub Check: Check Rust code with rustfmt and clippy
  • GitHub Check: Run snippets and cpython tests (windows-latest)
  • GitHub Check: Run snippets and cpython tests (ubuntu-latest)
  • GitHub Check: Run rust tests (ubuntu-latest)
  • GitHub Check: Ensure compilation on various targets
  • GitHub Check: Run rust tests (macos-latest)
  • GitHub Check: Run rust tests (windows-latest)
🔇 Additional comments (8)
vm/src/dict_inner.rs (5)

365-374: LGTM! Clean refactoring of the delete method.

The change from checking a boolean to checking is_some() maintains the same behavior while leveraging the new return type that provides the removed value.


376-381: Good backward compatibility wrapper.

The method correctly maintains the existing API while delegating to the new remove_if_exists method.


383-390: Well-designed conditional deletion method.

The new delete_if method provides a clean API for conditional removal with predicate support.


391-396: Clean implementation of value-returning removal.

The method correctly returns the removed value as Option<T>, providing more information to callers compared to the boolean-returning variant.


400-419: Correct implementation of the refactored remove_if method.

The method now returns the removed value, providing more useful information to callers while maintaining the same removal logic.

vm/src/builtins/dict.rs (1)

619-632: ```shell
#!/bin/bash

Search for other methods distinguishing exact vs non-exact dicts

rg -n "self\.exact_dict" -A2 -B2 vm/src/builtins/dict.rs


</details>
<details>
<summary>vm/src/builtins/type.rs (2)</summary>

`61-68`: **Good addition of dedicated qualname storage.**

The new `qualname` field in `HeapTypeExt` properly follows the same pattern as the `name` field, using `PyRwLock` for thread-safe access.



Also applies to: 177-177

---

`582-594`: **Correct implementation of __qualname__ getter.**

The getter properly returns the stored qualname for heap types with appropriate fallback to the type name, and returns the name directly for static types.

</details>

</blockquote></details>

</details>

<!-- This is an auto-generated comment by CodeRabbit for review status -->

@youknowone youknowone merged commit 5504f6d into RustPython:main Jun 27, 2025
12 checks passed
@youknowone youknowone deleted the heap-qualname branch June 27, 2025 10:58
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