Skip to content

more typing #5840

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 9 commits into from
Jun 26, 2025
Merged

more typing #5840

merged 9 commits into from
Jun 26, 2025

Conversation

youknowone
Copy link
Member

@youknowone youknowone commented Jun 26, 2025

Summary by CodeRabbit

  • New Features

    • Added an override decorator for marking functions as overrides.
    • Enhanced typing classes (ParamSpec, TypeVarTuple, ParamSpecArgs, ParamSpecKwargs) with new behaviors to prevent subclassing and unsupported operations.
    • Improved comparison logic for ParamSpecArgs and ParamSpecKwargs.
    • Refined module attribution for objects created in dynamic execution contexts.
  • Documentation

    • Updated documentation to clarify strict rules for modifying test code, including allowed and forbidden changes.
  • Chores

    • Removed outdated @unittest.expectedFailure decorators and related TODO comments from typing-related tests.
    • Refactored internal module naming and import paths for typing constructs.

Copy link

coderabbitai bot commented Jun 26, 2025

Caution

Review failed

The pull request is closed.

Walkthrough

This update introduces stricter documentation for test code modifications, refactors internal module naming and usage in the typing implementation, and enhances several typing-related classes with new magic methods and comparison logic. Test suite decorators and comments indicating expected failures are removed, and a new override decorator is added to the typing module.

Changes

File(s) Change Summary
.github/copilot-instructions.md Added section detailing strict rules for modifying test code, specifying allowed and forbidden changes with examples.
Lib/test/test_typing.py Removed @unittest.expectedFailure decorators and related # TODO: RUSTPYTHON comments; test logic remains unchanged.
vm/src/frame.rs Updated imports and usage from stdlib::typing::_typing to stdlib::typing for typing-related functions and types.
vm/src/stdlib/typing.rs Renamed _typing to decl, added override function, new magic methods for typing classes, improved comparison logic, and refined module attribution.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant PythonCode
    participant RustPythonTyping as Typing Module (decl)
    participant VM

    User->>PythonCode: Define function with @typing.override
    PythonCode->>RustPythonTyping: Call override(func)
    RustPythonTyping->>PythonCode: Set func.__override__ = True

    User->>PythonCode: Subclass ParamSpec/TypeVarTuple/ParamSpecArgs/ParamSpecKwargs
    PythonCode->>RustPythonTyping: Call mro_entries()
    RustPythonTyping->>PythonCode: Raise TypeError (subclassing not allowed)
Loading

Possibly related PRs

  • RustPython/RustPython#5837: Removes @unittest.expectedFailure decorators from the same Lib/test/test_typing.py tests, updating test expectations for typing constructs.
  • RustPython/RustPython#5834: Also removes @unittest.expectedFailure decorators from Lib/test/test_typing.py, addressing similar test expectation updates.

Suggested reviewers

  • arihant2math

Poem

In the warren of code where the type bunnies dwell,
New rules for our tests—now documented well!
With magic in typing and override in tow,
Our classes are stricter, comparisons now know.
No more expected failures, our tests hop with glee—
RustPython grows stronger, as swift as can be!
🐇✨


📜 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 d6e04aa and 166c7bc.

📒 Files selected for processing (1)
  • vm/src/stdlib/typing.rs (11 hunks)
✨ 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: 0

🧹 Nitpick comments (2)
vm/src/stdlib/typing.rs (2)

347-351: Minor inconsistency in error message formatting.

While the mro_entries implementations correctly prevent subclassing, there's an inconsistency in error message construction:

  • ParamSpec uses .to_owned() on a string literal (line 349)
  • Others use .to_owned() on formatted strings

Consider removing the unnecessary .to_owned() from the string literal:

-            Err(vm.new_type_error("Cannot subclass an instance of ParamSpec".to_owned()))
+            Err(vm.new_type_error("Cannot subclass an instance of ParamSpec"))

Also applies to: 654-658, 756-760, 835-839


788-825: Consider extracting common comparison logic to reduce duplication.

Both ParamSpecArgs and ParamSpecKwargs have identical comparison implementations. This violates the DRY principle.

Extract the common logic into a helper function:

fn compare_by_origin<T>(
    origin: &PyObjectRef,
    other: &PyObject,
    op: PyComparisonOp,
    vm: &VirtualMachine,
) -> PyResult<PyComparisonValue> {
    let eq = |other: PyObjectRef| -> PyResult<bool> {
        if let Ok(other_origin) = other.get_attr("__origin__", vm) {
            return Ok(origin.is(&other_origin));
        }
        Ok(false)
    };
    
    match op {
        PyComparisonOp::Eq => eq(other.to_owned())
            .map(Into::into)
            .unwrap_or(PyComparisonValue::NotImplemented),
        PyComparisonOp::Ne => eq(other.to_owned())
            .map(|result| (!result).into())
            .unwrap_or(PyComparisonValue::NotImplemented),
        _ => Ok(PyComparisonValue::NotImplemented),
    }
}

Then use it in both implementations:

impl Comparable for ParamSpecArgs {
    fn cmp(
        zelf: &crate::Py<Self>,
        other: &PyObject,
        op: PyComparisonOp,
        vm: &VirtualMachine,
    ) -> PyResult<PyComparisonValue> {
        compare_by_origin(&zelf.__origin__, other, op, vm)
    }
}

Also applies to: 867-904

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 6905d43 and d6e04aa.

📒 Files selected for processing (4)
  • .github/copilot-instructions.md (1 hunks)
  • Lib/test/test_typing.py (0 hunks)
  • vm/src/frame.rs (6 hunks)
  • vm/src/stdlib/typing.rs (8 hunks)
💤 Files with no reviewable changes (1)
  • Lib/test/test_typing.py
🧰 Additional context used
🧠 Learnings (3)
.github/copilot-instructions.md (8)
Learnt from: CR
PR: RustPython/RustPython#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-06-24T23:38:13.314Z
Learning: For documentation in RustPython, generate it with 'cargo doc --no-deps --all' and consult the architecture and development guide documents for further information.
Learnt from: CR
PR: RustPython/RustPython#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-06-24T23:38:13.314Z
Learning: For Rust code in the RustPython project, always run 'cargo clippy' to lint code before completing tasks, and fix any warnings or lints introduced by your changes.
Learnt from: CR
PR: RustPython/RustPython#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-06-24T23:38:13.314Z
Learning: In most cases, Python code in RustPython should not be edited; bug fixes should be made through Rust code modifications.
Learnt from: CR
PR: RustPython/RustPython#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-06-24T23:38:13.314Z
Learning: Follow Rust best practices for error handling and memory management when contributing to RustPython.
Learnt from: CR
PR: RustPython/RustPython#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-06-24T23:38:13.314Z
Learning: For Rust code in the RustPython project, always use the default rustfmt code style by running 'cargo fmt' to format code.
Learnt from: CR
PR: RustPython/RustPython#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-06-24T23:38:13.314Z
Learning: To determine what to implement next in RustPython, run './whats_left.py' to get a list of unimplemented methods.
Learnt from: CR
PR: RustPython/RustPython#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-06-24T23:38:13.314Z
Learning: Minimize modifications to CPython standard library files in the Lib/ directory of RustPython.
Learnt from: CR
PR: RustPython/RustPython#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-06-24T23:38:13.314Z
Learning: For custom Python code in RustPython, follow PEP 8 style and use ruff for linting.
vm/src/frame.rs (2)
Learnt from: CR
PR: RustPython/RustPython#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-06-24T23:38:13.314Z
Learning: When implementing Python functionality in Rust for RustPython, use the macro system such as 'pyclass', 'pymodule', and 'pyfunction'.
Learnt from: CR
PR: RustPython/RustPython#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-06-24T23:38:13.314Z
Learning: Follow Rust best practices for error handling and memory management when contributing to RustPython.
vm/src/stdlib/typing.rs (3)
Learnt from: CR
PR: RustPython/RustPython#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-06-24T23:38:13.314Z
Learning: When adding a Python module implemented in Rust to the RustPython interpreter, use 'vm.add_native_module' with the module name and the module's make_module function.
Learnt from: CR
PR: RustPython/RustPython#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-06-24T23:38:13.314Z
Learning: When implementing Python functionality in Rust for RustPython, use the macro system such as 'pyclass', 'pymodule', and 'pyfunction'.
Learnt from: CR
PR: RustPython/RustPython#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-06-24T23:38:13.314Z
Learning: For documentation in RustPython, generate it with 'cargo doc --no-deps --all' and consult the architecture and development guide documents for further information.
🧬 Code Graph Analysis (1)
vm/src/frame.rs (1)
vm/src/stdlib/typing.rs (9)
  • make_typevar (311-329)
  • bound (98-110)
  • bound (376-381)
  • new (918-928)
  • name (78-80)
  • name (353-355)
  • name (619-621)
  • make_paramspec (563-573)
  • make_typevartuple (739-745)
🪛 markdownlint-cli2 (0.17.2)
.github/copilot-instructions.md

188-188: Emphasis used instead of a heading
null

(MD036, no-emphasis-as-heading)

⏰ 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 (ubuntu-latest)
  • GitHub Check: Ensure compilation on various targets
  • GitHub Check: Run tests under miri
  • GitHub Check: Run snippets and cpython tests (macos-latest)
  • GitHub Check: Check Rust code with rustfmt and clippy
  • GitHub Check: Run snippets and cpython tests on wasm-wasi
  • GitHub Check: Run rust tests (ubuntu-latest)
  • GitHub Check: Check the WASM package and demo
  • GitHub Check: Run rust tests (macos-latest)
  • GitHub Check: Run rust tests (windows-latest)
🔇 Additional comments (6)
.github/copilot-instructions.md (1)

186-206: LGTM! Clear documentation of test modification rules.

The new section provides explicit guidelines for handling test code modifications, which aligns well with the changes made to test_typing.py where @unittest.expectedFailure decorators were removed.

vm/src/stdlib/typing.rs (4)

3-14: Module renaming is well-executed.

The internal module rename from _typing to decl improves code clarity while maintaining the external API through the #[pymodule(name = "_typing")] attribute.


47-53: Correct implementation of the override decorator.

The function properly implements PEP 698's @override decorator by setting the __override__ attribute, which matches CPython's behavior.


659-674: LGTM! Proper handling of TypeVarTuple substitution.

The implementation correctly prevents bare TypeVarTuple substitution and delegates complex preparation logic to the typing module.


983-996: Proper handling of exec contexts in module attribution.

The updated logic correctly handles cases where no module name is available (e.g., in exec contexts) by explicitly setting __module__ to None, which aligns with CPython's behavior.

vm/src/frame.rs (1)

20-20: Import paths correctly updated to match typing module refactoring.

All references have been consistently updated from typing::_typing:: to typing:: following the module restructuring.

Also applies to: 1237-1290

@youknowone youknowone merged commit 3031d5b into RustPython:main Jun 26, 2025
10 of 12 checks passed
@youknowone youknowone deleted the typing branch June 26, 2025 12:51
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