Skip to content

Align is_instance #5855

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 28, 2025
Merged

Align is_instance #5855

merged 3 commits into from
Jun 28, 2025

Conversation

youknowone
Copy link
Member

@youknowone youknowone commented Jun 28, 2025

Summary by CodeRabbit

  • Bug Fixes

    • Improved type and instance checking to better match Python's behavior, including correct handling of union types and tuples in isinstance checks.
    • Enhanced recursion protection during custom instance checks to prevent infinite loops.
  • Refactor

    • Updated internal logic for instance checking to align more closely with standard Python implementations.

Copy link

coderabbitai bot commented Jun 28, 2025

Walkthrough

The changes refactor type instance and subclass checking in the virtual machine. The __instancecheck__ method on PyType now accepts a VirtualMachine argument and returns PyResult<bool>, delegating to a new real_is_instance method. The is_instance and is_subclass methods are enhanced to handle union types, reorder checks to match CPython, and avoid infinite recursion by using real_is_instance.

Changes

File(s) Change Summary
vm/src/builtins/type.rs Modified PyType::__instancecheck__ signature to include vm and return PyResult<bool>. Updated implementation to use real_is_instance.
vm/src/protocol/object.rs Added real_is_instance method to PyObject. Refactored is_instance and is_subclass to handle union types, reorder checks, and avoid recursion.
Lib/test/test_isinstance.py Adjusted imports and recursion depth in tests. Changed union type order in one test. Minor whitespace and formatting cleanup.

Sequence Diagram(s)

sequenceDiagram
    participant Caller
    participant PyType
    participant PyObject
    participant VirtualMachine

    Caller->>PyType: __instancecheck__(obj, vm)
    PyType->>PyObject: real_is_instance(self.as_object(), vm)
    PyObject->>VirtualMachine: (uses vm for context)
    PyObject-->>PyType: PyResult<bool>
    PyType-->>Caller: PyResult<bool>
Loading
sequenceDiagram
    participant Caller
    participant PyObject
    participant VirtualMachine

    Caller->>PyObject: is_instance(cls, vm)
    alt cls is a type
        PyObject->>PyObject: real_is_instance(cls, vm)
    else cls is a union
        loop each member in union
            PyObject->>PyObject: is_instance(member, vm)
        end
    else cls is a tuple
        loop each member in tuple
            PyObject->>PyObject: is_instance(member, vm)
        end
    else cls has __instancecheck__
        PyObject->>cls: __instancecheck__(self, vm)
    else
        PyObject->>PyObject: real_is_instance(cls, vm)
    end
    PyObject-->>Caller: PyResult<bool>
Loading

Poem

In the warren of types, a new path we define,
With real_is_instance, the checks are more fine.
No more recursion traps, nor confusion in sight,
Union and tuple types now handled just right.
With each hop and check, our logic aligns—
A rabbit’s delight in these elegant lines! 🐇


📜 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 1b40c45 and dd90515.

📒 Files selected for processing (3)
  • Lib/test/test_isinstance.py (7 hunks)
  • vm/src/builtins/type.rs (1 hunks)
  • vm/src/protocol/object.rs (4 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • vm/src/builtins/type.rs
  • vm/src/protocol/object.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_isinstance.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_isinstance.py
🧠 Learnings (1)
Lib/test/test_isinstance.py (1)
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.
⏰ Context from checks skipped due to timeout of 90000ms (11)
  • GitHub Check: Run snippets and cpython tests (macos-latest)
  • GitHub Check: Check Rust code with rustfmt and clippy
  • GitHub Check: Run tests under miri
  • GitHub Check: Run snippets and cpython tests on wasm-wasi
  • GitHub Check: Run snippets and cpython tests (windows-latest)
  • GitHub Check: Check the WASM package and demo
  • GitHub Check: Run rust tests (windows-latest)
  • GitHub Check: Run snippets and cpython tests (ubuntu-latest)
  • GitHub Check: Run rust tests (macos-latest)
  • GitHub Check: Run rust tests (ubuntu-latest)
  • GitHub Check: Ensure compilation on various targets
🔇 Additional comments (3)
Lib/test/test_isinstance.py (3)

355-356: Approve import localization improvement.

Moving the sys import from module level to function level improves code organization by placing the import close to its usage.


227-227: Verify that union type order change is necessary and doesn't alter test intent.

The order of types in the union was changed from (int | str | list[int] | float) to (float | str | list[int] | int). According to coding guidelines, test data modifications in Lib/test files should be avoided.

Please confirm this change is necessary to align with core implementation behavior and doesn't fundamentally alter the test's intent:

#!/bin/bash
# Description: Search for related changes in core isinstance/issubclass implementation
# Expected: Find evidence of union type ordering changes in core files

rg -A 5 -B 5 "union.*type.*order|type.*union.*order" 
ast-grep --pattern 'isinstance($_, $union_type)' 

313-313: Verify recursion depth parameter changes align with core implementation.

The support.infinite_recursion() calls now include a depth parameter of 25. This appears to accommodate core implementation changes but modifies test behavior.

Please verify these parameter changes are necessary:

#!/bin/bash
# Description: Check for changes in infinite_recursion support function and core recursion handling
# Expected: Find evidence of recursion depth changes in core or test support

rg -A 3 -B 3 "infinite_recursion.*25|recursion.*25"
ast-grep --pattern 'infinite_recursion($depth)'
rg "support\.infinite_recursion" --type py

Also applies to: 347-347

✨ 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 merged commit 2bd5212 into RustPython:main Jun 28, 2025
12 checks passed
@youknowone youknowone deleted the is-instance branch June 28, 2025 02:59
This was referenced Jun 29, 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