Skip to content

Update isintance #5868

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 3 commits into from
Jun 29, 2025
Merged

Update isintance #5868

merged 3 commits into from
Jun 29, 2025

Conversation

youknowone
Copy link
Member

@youknowone youknowone commented Jun 29, 2025

Summary by CodeRabbit

  • Bug Fixes

    • Improved reliability of subclass and instance checks involving union types and tuples, ensuring more consistent behavior in type checks.
  • New Features

    • Added a way to directly access the arguments of union types, aligning with standard Python behavior.

Copy link

coderabbitai bot commented Jun 29, 2025

Walkthrough

A public accessor method args() was added to the PyUnion struct for direct access to its internal tuple of arguments. The is_subclass and is_instance methods in PyObject were updated to use direct downcasting and the new accessor for union type checks, simplifying and unifying the handling of unions and tuples.

Changes

File(s) Change Summary
vm/src/builtins/union.rs Added pub fn args(&self) -> &PyTupleRef to PyUnion for direct access to the args field.
vm/src/protocol/object.rs Updated is_subclass and is_instance to downcast to PyUnion and use args() for checks; unified tuple handling.

Sequence Diagram(s)

sequenceDiagram
    participant Caller
    participant PyObject
    participant PyUnion

    Caller->>PyObject: is_subclass(cls)
    alt cls is PyUnion
        PyObject->>PyUnion: args()
        PyObject->>PyObject: is_subclass(member) for each member in args
    else cls is tuple
        PyObject->>PyObject: is_subclass(member) for each member in tuple
    else
        PyObject->>PyObject: __subclasscheck__ or default check
    end
Loading

Possibly related PRs

  • RustPython/RustPython#5855: Adds the same args() accessor and updates union handling in is_subclass and is_instance, directly refining the code in this PR.

Poem

A tuple of unions, a method anew,
Now args() reveals what unions construe.
Subclass and instance, with checks more direct,
No more indirection—just what you'd expect!
With code now more clear,
The rabbit gives cheer:
🐇 "Union logic, hop-hop, perfect!"

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

@youknowone youknowone changed the title Isinstance Update isintance Jun 29, 2025
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

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 47a7a00 and f26054a.

📒 Files selected for processing (2)
  • vm/src/builtins/union.rs (1 hunks)
  • vm/src/protocol/object.rs (2 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
vm/src/protocol/object.rs (3)
vm/src/protocol/sequence.rs (1)
  • tuple (279-289)
vm/src/builtins/union.rs (1)
  • __subclasscheck__ (122-136)
vm/src/builtins/type.rs (2)
  • __subclasscheck__ (1247-1251)
  • typ (1053-1061)
⏰ Context from checks skipped due to timeout of 90000ms (11)
  • GitHub Check: Run snippets and cpython tests on wasm-wasi
  • GitHub Check: Check the WASM package and demo
  • 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 (windows-latest)
  • 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 (5)
vm/src/builtins/union.rs (1)

43-47: LGTM! Well-implemented accessor method.

The new args() method provides clean, direct access to the union's arguments and properly aligns with CPython's _Py_union_args approach. The implementation follows Rust conventions with appropriate inlining and documentation.

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

500-506: Variable rename improves clarity.

The rename from self to derived makes the subclass checking logic more explicit and readable.


532-539: Variable naming improvements enhance readability.

The standardization of variable names (methchecker, retres) improves code consistency and clarity.


605-615: Consistent union handling implementation.

The refactoring to use direct downcasting and the new args() method is well-implemented and consistent with the is_subclass changes. However, the same .expect() concern applies here.

The logic correctly handles union types, but consider the same defensive error handling suggestion as in is_subclass:

-            let union = cls
-                .try_to_ref::<crate::builtins::PyUnion>(vm)
-                .expect("checked by is");
+            let union = cls
+                .try_to_ref::<crate::builtins::PyUnion>(vm)
+                .map_err(|_| vm.new_type_error("Invalid union type"))?;

510-519: Union downcasting .expect() is safe here

The preceding cls.class().is(vm.ctx.types.union_type) check guarantees that the object is indeed a PyUnion, so the downcast_ref(...).expect(...) can never fail in normal operation. This is an internal invariant check rather than user-facing error handling, matching the existing pattern (e.g. the expect calls in vm/src/frame.rs for tuple downcasts). No change required.

Comment on lines +522 to 529
if let Some(tuple) = cls.downcast_ref::<PyTuple>() {
for item in tuple {
if vm.with_recursion("in __subclasscheck__", || derived.is_subclass(item, vm))? {
return Ok(true);
}
}
return Ok(false);
}
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Inconsistent tuple handling between methods.

The is_subclass method uses downcast_ref::<PyTuple>() while is_instance (line 618) uses try_to_ref::<PyTuple>(vm). This inconsistency could lead to different error handling behavior.

Standardize tuple handling across both methods. Consider using the same approach:

-        if let Some(tuple) = cls.downcast_ref::<PyTuple>() {
+        if let Ok(tuple) = cls.try_to_ref::<PyTuple>(vm) {

Or alternatively, update is_instance to match this pattern for consistency.

📝 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(tuple) = cls.downcast_ref::<PyTuple>() {
for item in tuple {
if vm.with_recursion("in __subclasscheck__", || derived.is_subclass(item, vm))? {
return Ok(true);
}
}
return Ok(false);
}
if let Ok(tuple) = cls.try_to_ref::<PyTuple>(vm) {
for item in tuple {
if vm.with_recursion("in __subclasscheck__", || derived.is_subclass(item, vm))? {
return Ok(true);
}
}
return Ok(false);
}
🤖 Prompt for AI Agents
In vm/src/protocol/object.rs around lines 522 to 529, the method uses
downcast_ref::<PyTuple>() to handle tuples, while is_instance at line 618 uses
try_to_ref::<PyTuple>(vm), causing inconsistent tuple handling and error
behavior. To fix this, standardize tuple handling by either changing is_subclass
to use try_to_ref with the vm parameter like is_instance, or update is_instance
to use downcast_ref without vm, ensuring both methods handle tuples the same way
and maintain consistent error handling.

@youknowone youknowone merged commit 7c6d063 into RustPython:main Jun 29, 2025
12 checks passed
@youknowone youknowone deleted the isinstance branch June 29, 2025 06:15
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