Skip to content

Add sys._getframemodulename #5873

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 30, 2025

Conversation

youknowone
Copy link
Member

@youknowone youknowone commented Jun 30, 2025

Summary by CodeRabbit

  • New Features

    • Added a new function to the sys module that allows retrieving the module name of a function at a specified depth in the call stack.
  • Tests

    • Introduced tests to verify the correct behavior of the new sys module function for retrieving function module names.
  • Chores

    • Updated the spelling dictionary to recognize a new Python-related term.

Copy link

coderabbitai bot commented Jun 30, 2025

Walkthrough

This change introduces a new function, sys._getframemodulename, to the Python VM, enabling retrieval of the __module__ attribute for the function object associated with a frame at a specified call stack depth. Supporting changes propagate function objects into frames, update frame construction, and add corresponding tests and dictionary entries.

Changes

File(s) Change Summary
.cspell.dict/python-more.txt Added the term getframemodulename to the spelling dictionary.
extra_tests/snippets/stdlib_sys.py Added tests for sys._getframemodulename, including a custom function with a set module attribute.
vm/src/builtins/function.rs Closed an impl block, added an inherent impl for Py<PyFunction>, and updated frame creation to pass the function object.
vm/src/frame.rs Added func_obj: Option<PyObjectRef> field to Frame and updated its constructor to accept this.
vm/src/stdlib/sys.rs Added new function _getframemodulename to the sys module, exposing module name retrieval for frames.
vm/src/vm/mod.rs Modified run_code_obj to create a PyFunction for module code and pass it to frame creation.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant PythonVM
    participant sys._getframemodulename
    participant Frame
    participant FunctionObject

    User->>PythonVM: Call sys._getframemodulename(depth)
    PythonVM->>Frame: Access frame at given depth
    Frame->>FunctionObject: Retrieve associated function object
    FunctionObject->>PythonVM: Return __module__ attribute
    PythonVM->>User: Return module name or None
Loading

Poem

In the warren of frames, a module’s name gleams,
Now sys can reveal it, or so it now seems!
With function and frame, the stack’s not the same—
A hop through the code, and modules we claim.
🐇✨


📜 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 3bde2dd and 09a882a.

📒 Files selected for processing (6)
  • .cspell.dict/python-more.txt (1 hunks)
  • extra_tests/snippets/stdlib_sys.py (1 hunks)
  • vm/src/builtins/function.rs (2 hunks)
  • vm/src/frame.rs (3 hunks)
  • vm/src/stdlib/sys.rs (1 hunks)
  • vm/src/vm/mod.rs (1 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
`**/*.rs`: Follow the default rustfmt code style (`cargo fmt` to format) Always ...

**/*.rs: Follow the default rustfmt code style (cargo fmt to format)
Always run clippy to lint code (cargo clippy) before completing tasks. Fix any warnings or lints that are introduced by your changes
Follow Rust best practices for error handling and memory management
Use the macro system (pyclass, pymodule, pyfunction, etc.) when implementing Python functionality in Rust

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

List of files the instruction was applied to:

  • vm/src/frame.rs
  • vm/src/vm/mod.rs
  • vm/src/stdlib/sys.rs
  • vm/src/builtins/function.rs
`**/*.py`: Follow PEP 8 style for custom Python code Use ruff for linting Python code

**/*.py: Follow PEP 8 style for custom Python code
Use ruff for linting Python code

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

List of files the instruction was applied to:

  • extra_tests/snippets/stdlib_sys.py
🧠 Learnings (3)
vm/src/vm/mod.rs (1)
Learnt from: CR
PR: RustPython/RustPython#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-06-30T10:08:48.851Z
Learning: Applies to **/*.rs : Use the macro system (`pyclass`, `pymodule`, `pyfunction`, etc.) when implementing Python functionality in Rust
vm/src/stdlib/sys.rs (3)
Learnt from: moreal
PR: RustPython/RustPython#5847
File: vm/src/stdlib/stat.rs:547-567
Timestamp: 2025-06-27T14:47:28.810Z
Learning: In RustPython's stat module implementation, platform-specific constants like SF_SUPPORTED and SF_SYNTHETIC should be conditionally declared only for the platforms where they're available (e.g., macOS), following CPython's approach of optional declaration rather than providing fallback values for other platforms.
Learnt from: moreal
PR: RustPython/RustPython#5847
File: vm/src/stdlib/stat.rs:547-567
Timestamp: 2025-06-27T14:47:28.810Z
Learning: In RustPython's stat module implementation, platform-specific constants like SF_SUPPORTED and SF_SYNTHETIC should be conditionally declared only for the platforms where they're available (e.g., macOS), following CPython's approach of optional declaration using #ifdef checks rather than providing fallback values for other platforms.
Learnt from: CR
PR: RustPython/RustPython#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-06-30T10:08:48.851Z
Learning: Applies to **/*.rs : Use the macro system (`pyclass`, `pymodule`, `pyfunction`, etc.) when implementing Python functionality in Rust
vm/src/builtins/function.rs (1)
Learnt from: CR
PR: RustPython/RustPython#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-06-30T10:08:48.851Z
Learning: Applies to **/*.rs : Use the macro system (`pyclass`, `pymodule`, `pyfunction`, etc.) when implementing Python functionality in Rust
🧬 Code Graph Analysis (2)
extra_tests/snippets/stdlib_sys.py (1)
vm/src/stdlib/sys.rs (1)
  • _getframemodulename (517-540)
vm/src/stdlib/sys.rs (4)
vm/src/builtins/function.rs (2)
  • __module__ (470-472)
  • __module__ (770-772)
vm/src/builtins/type.rs (2)
  • __module__ (742-756)
  • module (1366-1366)
vm/src/builtins/classmethod.rs (1)
  • __module__ (139-141)
vm/src/builtins/staticmethod.rs (1)
  • __module__ (100-102)
🪛 Pylint (3.3.7)
extra_tests/snippets/stdlib_sys.py

[error] 151-151: Module 'sys' has no '_getframemodulename' member

(E1101)


[error] 151-151: Module 'sys' has no '_getframemodulename' member

(E1101)


[error] 155-155: Module 'sys' has no '_getframemodulename' member

(E1101)

⏰ Context from checks skipped due to timeout of 90000ms (11)
  • GitHub Check: Run snippets and cpython tests on wasm-wasi
  • GitHub Check: Run tests under miri
  • GitHub Check: Check the WASM package and demo
  • GitHub Check: Check Rust code with rustfmt and clippy
  • GitHub Check: Run snippets and cpython tests (macos-latest)
  • GitHub Check: Run rust tests (windows-latest)
  • GitHub Check: Run snippets and cpython 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 (13)
vm/src/frame.rs (1)

100-100: LGTM! Clean integration of func_obj field.

The addition of the optional func_obj field to the Frame struct is well-implemented:

  • Uses Option<PyObjectRef> for proper memory management and null safety
  • Public visibility enables access from other VM components
  • Constructor properly accepts and initializes the new parameter
  • Maintains backward compatibility with existing code

Also applies to: 143-143, 165-165

.cspell.dict/python-more.txt (1)

81-81: LGTM! Proper dictionary update for the new function name.

The addition of getframemodulename to the spell check dictionary is correctly placed in alphabetical order and necessary to support the new sys._getframemodulename() function.

extra_tests/snippets/stdlib_sys.py (1)

151-160: Good basic test coverage for the new functionality.

The tests effectively validate the core functionality of sys._getframemodulename():

  • Tests the default case returning "__main__" from module scope
  • Tests custom __module__ attribute retrieval
  • Demonstrates proper function object integration

The static analysis hints about missing sys member are expected for this new feature and can be safely ignored.

Consider adding tests for additional scenarios in future iterations:

  • Testing with the depth parameter
  • Testing behavior when __module__ attribute is missing
  • Testing with nested function calls to validate frame depth handling
vm/src/builtins/function.rs (3)

318-318: LGTM: Proper closure of implementation block.

The closing brace correctly terminates the impl PyFunction block.


320-320: LGTM: New implementation block follows Rust conventions.

The new impl Py<PyFunction> block is properly structured and follows the codebase patterns for implementing methods on Py<T> wrapper types.


357-357: LGTM: Function object association implemented correctly.

The addition of Some(self.to_owned().into()) as a parameter correctly passes the function object to the frame constructor. The conversion from Py<PyFunction> to PyObjectRef using .into() is idiomatic and type-safe in the RustPython codebase.

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

516-517: LGTM: Function signature follows established patterns.

The function signature with #[pyfunction] decorator and OptionalArg<usize> parameter type follows the established patterns in the sys module, consistent with similar functions like _getframe.


518-524: LGTM: Depth validation and bounds checking implemented correctly.

The depth parameter handling and bounds checking logic mirrors the existing _getframe function implementation, ensuring consistency in error handling across similar sys module functions.


525-526: LGTM: Frame access follows established pattern.

The frame stack indexing logic (len - depth - 1) correctly mirrors the implementation in _getframe, ensuring consistent behavior across frame-related sys functions.


528-540: LGTM: Error handling mimics CPython behavior correctly.

The implementation correctly handles the case where the frame has no function object (returns None) and appropriately catches attribute access errors to return None instead of propagating them, which matches CPython's behavior of clearing errors and returning None for sys._getframemodulename.

vm/src/vm/mod.rs (3)

452-452: LGTM: Import statement properly added.

The import of PyFunction is correctly placed and necessary for the function object creation in the modified run_code_obj method.


454-468: LGTM: Function object creation follows CPython approach.

The creation of a PyFunction object to represent module-level code correctly aligns with CPython's approach. The parameter choices are appropriate:

  • code.clone() and scope.globals.clone() properly reference the execution context
  • None values for closure, defaults, and kwdefaults are correct for module code
  • qualname derived from code.obj_name is appropriate
  • Empty tuples/dicts for type_params and annotations follow the expected defaults
  • self.ctx.none() for doc is consistent with module code having no docstring by default

469-471: LGTM: Frame creation properly updated with function object.

The conversion of the function to a reference (func.into_ref(&self.ctx).into()) and passing it as Some(func_obj) to Frame::new correctly implements the frame-function association needed for the new sys._getframemodulename functionality.

✨ 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 force-pushed the getframemodulename branch from b2dc7a1 to 09a882a Compare June 30, 2025 11:36
@youknowone youknowone marked this pull request as ready for review June 30, 2025 11:36
@youknowone youknowone merged commit d5d3507 into RustPython:main Jun 30, 2025
12 checks passed
@youknowone youknowone deleted the getframemodulename branch June 30, 2025 13:50
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