Skip to content

Pyfunction builtins and constructor #5823

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 2 commits into from
Jun 24, 2025
Merged

Conversation

youknowone
Copy link
Member

@youknowone youknowone commented Jun 23, 2025

Summary by CodeRabbit

  • New Features

    • Added support for accessing the built-in namespace from Python function objects.
    • Enabled creation of Python function objects directly from Python code with enhanced argument options.
  • Bug Fixes

    • Improved validation for function closures to ensure correct structure and compatibility.
  • Refactor

    • Streamlined function object creation, removing redundant attribute assignments and simplifying argument handling.
  • Tests

    • Removed expected failure marker from a namedtuple test, indicating resolved test stability.

Copy link

coderabbitai bot commented Jun 23, 2025

Walkthrough

The changes update the PyFunction struct to include a builtins field and modify its constructor to initialize this field using the provided globals or context. The constructor now returns a PyResult. Python-level construction of PyFunction is enabled via a new argument struct and trait implementation. Related adjustments are made in function creation logic, removing explicit attribute settings and module retrieval. A test decorator marking expected failure was removed.

Changes

File(s) Change Summary
vm/src/builtins/function.rs Added builtins field to PyFunction, updated constructor to set it, changed return type to PyResult, added Python-level constructor and argument parsing, exposed builtins as a property.
vm/src/frame.rs Updated function creation to match new PyFunction::new signature, removed explicit setting of __name__, __qualname__, and __doc__, and omitted module retrieval.
Lib/test/test_collections.py Removed @unittest.expectedFailure decorator and preceding TODO comment from test_new_builtins_issue_43102 test method.

Sequence Diagram(s)

sequenceDiagram
    participant VM as VirtualMachine
    participant Frame as ExecutingFrame
    participant PyFunc as PyFunction

    Frame->>VM: Request to create PyFunction (with code, globals, etc.)
    VM->>PyFunc: Call PyFunction::new(...) with vm reference
    PyFunc->>PyFunc: Initialize builtins from globals or VM context
    PyFunc-->>VM: Return new PyFunction or error
    VM-->>Frame: Push PyFunction to stack
Loading

Poem

In the warren of code, a function was born,
With builtins now bundled, its logic adorned.
Constructors made clever, with arguments new,
Python can craft it, as rabbits would do.
A hop and a skip, through globals it gleans—
The magic of builtins, now part of its means!
🐇✨


📜 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 edb7934 and 67dbf42.

📒 Files selected for processing (3)
  • Lib/test/test_collections.py (0 hunks)
  • vm/src/builtins/function.rs (7 hunks)
  • vm/src/frame.rs (1 hunks)
💤 Files with no reviewable changes (1)
  • Lib/test/test_collections.py
🚧 Files skipped from review as they are similar to previous changes (1)
  • vm/src/frame.rs
🧰 Additional context used
📓 Path-based instructions (1)
`**/*.rs`: Follow the default rustfmt code style; use 'cargo fmt' to format Rust code. Always run clippy to lint Rust code ('cargo clippy') before completing tasks, and fix any war...

**/*.rs: Follow the default rustfmt code style; use 'cargo fmt' to format Rust code.
Always run clippy to lint Rust code ('cargo clippy') before completing tasks, and fix any warnings or lints introduced by your changes.

  • vm/src/builtins/function.rs
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Check Rust code with rustfmt and clippy
🔇 Additional comments (6)
vm/src/builtins/function.rs (6)

34-34: LGTM! Proper struct field addition.

The new builtins field is correctly added to the struct and follows the existing pattern.


57-103: Well-implemented constructor changes with proper error handling.

The constructor changes are well-structured:

  • Proper parameter addition for VirtualMachine
  • Correct fallback logic for builtins resolution
  • Appropriate error propagation with PyResult

The builtins resolution logic properly handles the hierarchy: globals → current frame → VM builtins.


385-385: LGTM! Proper trait addition for constructor support.

The Constructor trait is correctly added to enable Python-level construction of PyFunction objects.


429-433: LGTM! Well-implemented builtins getter method.

The getter method correctly follows the existing pattern for accessing the builtins field and properly handles the PyResult return type.


584-598: LGTM! Well-structured argument struct for constructor.

The PyFunctionNewArgs struct properly defines the required and optional arguments with appropriate types and decorators.


600-657: Comprehensive constructor implementation with proper validation.

The Constructor implementation is well-structured with:

  • Proper closure validation and length checking
  • Appropriate error messages for validation failures
  • Correct handling of optional parameters
  • Proper type conversion for the tuple of cells

The implementation follows Rust and PyO3 best practices for constructor functions.

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

Comment on lines +97 to +100
// let name = qualname.as_str().split('.').next_back().unwrap();
// func.set_attr(identifier!(vm, __name__), vm.new_pyobj(name), vm)?;
// func.set_attr(identifier!(vm, __qualname__), qualname, vm)?;
// func.set_attr(identifier!(vm, __doc__), doc, vm)?;
Copy link
Member Author

Choose a reason for hiding this comment

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

check if this is required

@youknowone youknowone merged commit 3566dca into RustPython:main Jun 24, 2025
12 checks passed
@youknowone youknowone deleted the pyfunction branch June 24, 2025 01:23
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