vm.run_pyc_bytes by youknowone · Pull Request #6645 · RustPython/RustPython
Repository navigation
vm.run_pyc_bytes - #6645
Merged
youknowone merged 5 commits into RustPython:main from youknowone:run_pyc_bytes Jan 4, 2026
Merged
vm.run_pyc_bytes #6645 youknowone merged 5 commits into RustPython:main from youknowone:run_pyc_bytes
Conversation
youknowone
commented
Jan 4, 2026
·
edited by coderabbitai
Bot
Loading
Copy link Copy Markdown
Member
Fix #6239
Summary by CodeRabbit
-
New Features
- Support for loading and executing precompiled Python bytecode (.pyc) from files or in-memory bytes
- New VM API to run bytecode directly from memory and a new helper to create a main scope
-
Refactor
- Simplified main-run flow and scope initialization, consolidating setup and cleanup behavior
✏️ Tip: You can customize this high-level summary in your review settings.
youknowone added 3 commits January 4, 2026 20:54
rustpython_vm::import::check_pyc_magic_number_bytes
20aacae
vm.new_scope_with_main
0a4a153
PyCode::from_pyc
7e33efa
coderabbitai
Bot
commented
Jan 4, 2026
·
edited
Loading
Copy link Copy Markdown
Contributor
📝 Walkthrough
WalkthroughThis PR adds APIs and helpers to load and execute .pyc bytecode from memory or files: new PyCode constructors to build code objects from pyc bytes/paths, a VM API to run pyc bytes, a centralized pyc magic-number check, and refactors main-scope/module initialization to a VM-provided helper. Changes
Sequence DiagramsequenceDiagram
autonumber
actor Client
participant VM as VirtualMachine
participant Scope
participant MainMod as __main__ Module
participant PyCode
participant FrozenImportlib as frozen_importlib._compile_bytecode
Client->>VM: run_pyc_bytes(pyc_bytes, scope)
activate VM
VM->>VM: with_simple_run("__main__", closure)
VM->>Scope: ensure scope / builtins (new_scope_with_main)
VM->>MainMod: create/register __main__, init __annotations__
Note right of VM: Inject __file__ / __cached__ into MainMod
VM->>PyCode: from_pyc(pyc_bytes, metadata, vm)
activate PyCode
PyCode->>PyCode: check_pyc_magic_number_bytes(pyc_bytes)
PyCode->>FrozenImportlib: load & call _compile_bytecode(bytes, metadata)
FrozenImportlib-->>PyCode: code object
deactivate PyCode
PyCode-->>VM: return PyCode
VM->>MainMod: execute code object in __main__ dict
Note right of VM: flush IO / cleanup injected state
deactivate VM
VM-->>Client: PyResult<()>
Loading
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Possibly related PRs
Suggested reviewers
Poem
Pre-merge checks and finishing touches✅ Passed checks (5 passed)
📜 Recent review details Configuration used : Path: .coderabbit.yml Review profile : CHILL Plan : Pro 📥 CommitsReviewing files that changed from the base of the PR and between 5e90531 and 8634a91 . 📒 Files selected for processing (2)
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. ❤️ ShareComment |
vm.run_pyc_bytes
5e90531
youknowone
force-pushed
the
run_pyc_bytes
branch
from
0b1cd18 to
5e90531
Compare
January 4, 2026 12:16 youknowone marked this pull request as ready for review January 4, 2026 12:53 coderabbitai
Bot
reviewed Jan 4, 2026
View reviewed changes
coderabbitai
Bot
left a comment
Copy link Copy Markdown
Contributor
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more .
Actionable comments posted: 2
🧹 Nitpick comments (2)crates/vm/src/vm/vm_new.rs (1)📜 Review detailscrates/vm/src/builtins/code.rs (1)
65-80: Consider propagating error instead of panicking on__annotations__initialization.Line 71 uses
🔎 Proposed fix.expect()which will panic if setting__annotations__fails, while the rest of the method uses?for error propagation. For consistency and robustness, consider using?here as well.pub fn new_scope_with_main(&self) -> PyResult<Scope> { let scope = self.new_scope_with_builtins(); let main_module = self.new_module("__main__", scope.globals.clone(), None); main_module .dict() - .set_item("__annotations__", self.ctx.new_dict().into(), self) - .expect("Failed to initialize __main__.__annotations__"); + .set_item("__annotations__", self.ctx.new_dict().into(), self)?; self.sys_module.get_attr("modules", self)?.set_item( "__main__", main_module.into(), self, )?; Ok(scope) }
339-352: Consider using actual source path instead of hardcoded"<source>".The
🔎 Proposed fixsource_pathis hardcoded to"<source>"which may be confusing in tracebacks. Consider deriving it from the path or allowing it to beNone.Self::from_pyc( &content, Some(&name), Some(&path.display().to_string()), - Some("<source>"), + None, // Let the loader determine the source path vm, )
Configuration used : Path: .coderabbit.yml
Review profile : CHILL
Plan : Pro
📥 CommitsReviewing files that changed from the base of the PR and between ec564ac and 5e90531 .
📒 Files selected for processing (6)crates/vm/src/builtins/code.rscrates/vm/src/import.rscrates/vm/src/vm/mod.rscrates/vm/src/vm/python_run.rscrates/vm/src/vm/vm_new.rssrc/lib.rs
📄 CodeRabbit inference engine (.github/copilot-instructions.md)
**/*.rs: Follow the default rustfmt code style by runningcargo fmtto format Rust code
Always run clippy to lint code (cargo clippy) before completing tasks and fix any warnings or lints introduced by 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
Files:
crates/vm/src/import.rssrc/lib.rscrates/vm/src/vm/vm_new.rscrates/vm/src/vm/mod.rscrates/vm/src/vm/python_run.rscrates/vm/src/builtins/code.rs
Learnt from: CR
Repo: RustPython/RustPython PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-12-27T14:03:49.034Z
Learning: When testing Python code, always use RustPython instead of the standard `python` command; use `cargo run -- script.py` or `cargo run` for interactive REPL
Applied to files:
src/lib.rscrates/vm/src/vm/mod.rscrates/vm/src/vm/python_run.rs
Learnt from: CR
Repo: RustPython/RustPython PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-12-27T14:03:49.034Z
Learning: When modifying bytecode instructions, perform a full clean build by running `rm -r target/debug/build/rustpython-* && find . | grep -E '\.pyc$' | xargs rm -r`
Applied to files:
crates/vm/src/vm/mod.rscrates/vm/src/vm/python_run.rs
Learnt from: CR
Repo: RustPython/RustPython PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-12-27T14:03:49.034Z
Learning: RustPython is a Python 3 interpreter written in Rust implementing Python 3.13.0+ compatibility with complete Python environment in Rust (not CPython bindings), clean implementation without compatibility hacks, and cross-platform support including WebAssembly compilation
Applied to files:
crates/vm/src/vm/mod.rs
Learnt from: CR
Repo: RustPython/RustPython PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-12-27T14:03:49.034Z
Learning: Applies to **/*.rs : Use the macro system (`pyclass`, `pymodule`, `pyfunction`, etc.) when implementing Python functionality in Rust
Applied to files:
crates/vm/src/vm/python_run.rs
crates/vm/src/builtins/code.rs (1)crates/vm/src/vm/python_run.rs (2)
from_pyc(353-370)
crates/vm/src/vm/mod.rs (1)crates/vm/src/builtins/code.rs (1)crates/vm/src/import.rs (1)
import(689-693)
check_pyc_magic_number_bytes(11-13)
crates/vm/src/import.rs (1)🔇 Additional comments (7)
check_pyc_magic_number_bytes(11-13)
src/lib.rs (2)crates/vm/src/vm/mod.rs (3)
209-209: LGTM!The refactoring to use
vm.new_scope_with_main()centralizes the main module initialization logic and improves maintainability.
354-360: LGTM!Test code correctly updated to use the new
new_scope_with_main()API.crates/vm/src/vm/python_run.rs (2)
463-497: Well-documented API with clear usage example.The
run_pyc_bytesimplementation correctly:
- Provides clear documentation with usage examples
- Delegates to
PyCode::from_pycfor loading- Uses
with_simple_runfor proper main module setupOne minor note: the path
"<source>"passed towith_simple_runis generic. Consider allowing callers to specify a more descriptive path in a future enhancement.
539-571: LGTM!The
with_simple_runhelper properly:
- Sets
__file__and__cached__only if not already set- Cleans up these attributes after execution
- Flushes IO streams
573-583: LGTM!The
flush_iohelper appropriately ignores errors during cleanup, which is the correct behavior for post-execution flushing.
27-31: LGTM!The refactoring to use
with_simple_runproperly centralizes the__file__and__cached__management, reducing code duplication.
133-150: LGTM!The magic number validation is now properly centralized through
check_pyc_magic_number_bytes. The function correctly validates that exactly 2 bytes were read before checking the magic.
add boundary check
8634a91
youknowone
force-pushed
the
run_pyc_bytes
branch
from
ecfaed3 to
8634a91
Compare
January 4, 2026 13:16 youknowone merged commit
e1b22f1
into
RustPython : main
Jan 4, 2026
youknowone
deleted the
run_pyc_bytes
branch
January 4, 2026 13:58
terryluan12
pushed a commit
to terryluan12/RustPython
that referenced
this pull request
Jan 5, 2026
vm.run_pyc_bytes (RustPython#6645)
6026f9a
* rustpython_vm::import::check_pyc_magic_number_bytes * vm.new_scope_with_main * PyCode::from_pyc * vm.run_pyc_bytes * add boundary checkcoderabbitai
Bot
mentioned this pull request Jan 5, 2026 Updated the re library + test #6648 Merged terryluan12 pushed a commit to terryluan12/RustPython that referenced this pull request Jan 5, 2026
vm.run_pyc_bytes (RustPython#6645)
4d0b984
* rustpython_vm::import::check_pyc_magic_number_bytes * vm.new_scope_with_main * PyCode::from_pyc * vm.run_pyc_bytes * add boundary checkterryluan12 pushed a commit to terryluan12/RustPython that referenced this pull request Jan 15, 2026
vm.run_pyc_bytes (RustPython#6645)
8ac0e53
* rustpython_vm::import::check_pyc_magic_number_bytes * vm.new_scope_with_main * PyCode::from_pyc * vm.run_pyc_bytes * add boundary checkcoderabbitai
Bot
mentioned this pull request Feb 17, 2026 Use _print_exception_bltin in excepthook, register source in linecache #7177 Merged coderabbitai
Bot
mentioned this pull request Mar 2, 2026 Lazy locals dict for NEWLOCALS frames #7307 Merged Sign up for free to join this conversation on GitHub . Already have an account? Sign in to comment