Py new#6402
Conversation
WalkthroughThis PR refactors constructor implementations for built-in Python types (bytes, frozenset, str, tuple) in RustPython, changing how constructor arguments are represented and processed. It moves construction logic from shared helpers into type-specific optimized paths, removes the Changes
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes
Specific areas requiring extra attention:
Possibly related PRs
Suggested reviewers
Poem
Pre-merge checks and finishing touches❌ Failed checks (1 warning, 1 inconclusive)
✅ Passed checks (1 passed)
✨ Finishing touches
🧪 Generate unit tests (beta)
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. Comment |
Sorry, something went wrong.
There was a problem hiding this comment.
Actionable comments posted: 1
📜 Review details
Configuration used: Path: .coderabbit.yml
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (6)
crates/vm/src/builtins/bytes.rs(1 hunks)crates/vm/src/builtins/set.rs(1 hunks)crates/vm/src/builtins/str.rs(1 hunks)crates/vm/src/builtins/tuple.rs(1 hunks)crates/vm/src/bytes_inner.rs(1 hunks)crates/vm/src/protocol/object.rs(2 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
**/*.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 Rust 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/builtins/set.rscrates/vm/src/builtins/tuple.rscrates/vm/src/builtins/bytes.rscrates/vm/src/builtins/str.rscrates/vm/src/bytes_inner.rscrates/vm/src/protocol/object.rs
🧠 Learnings (2)
📓 Common learnings
Learnt from: CR
Repo: RustPython/RustPython PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-11-29T12:17:28.606Z
Learning: Applies to Lib/**/*.py : Add a `# TODO: RUSTPYTHON` comment when modifications are made to files in the `Lib/` directory
Learnt from: youknowone
Repo: RustPython/RustPython PR: 6110
File: vm/src/frame.rs:1311-1316
Timestamp: 2025-08-26T05:20:54.540Z
Learning: In the RustPython codebase, only certain builtin types should be marked with the SEQUENCE flag for pattern matching. List and tuple are sequences, but bytes, bytearray, and range are not considered sequences in this context, even though they may implement sequence-like protocols.
Learnt from: youknowone
Repo: RustPython/RustPython PR: 6110
File: vm/src/frame.rs:1311-1316
Timestamp: 2025-08-26T05:20:54.540Z
Learning: In RustPython's pattern matching implementation, only certain builtin types should have the SEQUENCE flag: list and tuple are confirmed sequences. The user youknowone indicated that bytes, bytearray are not considered sequences in this context, even though they implement sequence-like protocols.
📚 Learning: 2025-11-29T12:17:28.606Z
Learnt from: CR
Repo: RustPython/RustPython PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-11-29T12:17:28.606Z
Learning: Applies to **/*.rs : Use the macro system (`pyclass`, `pymodule`, `pyfunction`, etc.) when implementing Python functionality in Rust
Applied to files:
crates/vm/src/protocol/object.rs
🧬 Code graph analysis (4)
crates/vm/src/builtins/set.rs (5)
crates/vm/src/builtins/bytes.rs (2)
slot_new(97-149)py_new(151-153)crates/vm/src/builtins/tuple.rs (3)
slot_new(115-146)input(122-122)py_new(148-152)crates/vm/src/builtins/complex.rs (1)
slot_new(154-167)crates/vm/src/builtins/float.rs (1)
slot_new(134-147)crates/vm/src/builtins/list.rs (1)
from_iter(47-49)
crates/vm/src/builtins/bytes.rs (3)
crates/vm/src/builtins/str.rs (5)
slot_new(353-366)py_new(368-386)elements(2118-2120)elements(2229-2231)elements(2351-2353)crates/vm/src/builtins/tuple.rs (2)
slot_new(115-146)py_new(148-152)crates/vm/src/builtins/float.rs (1)
slot_new(134-147)
crates/vm/src/builtins/str.rs (1)
crates/vm/src/stdlib/typing.rs (1)
args(157-159)
crates/vm/src/protocol/object.rs (2)
crates/vm/src/builtins/bytes.rs (4)
from(44-48)from(52-54)obj(114-114)slot_new(97-149)crates/vm/src/builtins/object.rs (1)
slot_new(35-111)
🔇 Additional comments (9)
crates/vm/src/bytes_inner.rs (1)
3-7: LGTM - Import cleanup aligns with removed functionality.The import changes (removing
identifier,PyTypeRef, and simplifyingpystrimport) are consistent with the removal of theget_bytes()method that previously depended on these. The remaining imports support theget_bytearray_inner()method which is still used by the bytes constructor.crates/vm/src/builtins/str.rs (2)
353-366: LGTM - Optimization for exact str type is correct.The early return optimization correctly:
- Checks for exact
strtype (not subclasses)- Ensures single positional argument with no kwargs
- Verifies the argument is already an exact
strThis matches CPython's behavior and avoids unnecessary string copying.
368-386: LGTM - Clean separation of payload creation logic.The
py_newhelper correctly handles all construction cases:
- Decoding with encoding parameter
- Converting via
str()without encoding- Empty string for missing input
The separation from
slot_newimproves code clarity and follows the pattern established in other builtins.crates/vm/src/builtins/set.rs (1)
921-958: LGTM - Constructor refactor follows the established pattern.The implementation correctly:
- Returns exact
frozensetinput as-is (line 929-933)- Returns empty frozenset singleton for missing iterable (line 936-938)
- Returns empty frozenset singleton for empty result (line 947-950)
- Delegates payload creation to
py_newwhich usesfrom_iterThe
type Args = Vec<PyObjectRef>declaration aligns withpy_new's signature, whileslot_newhandles the conversion fromFuncArgsto the expected elements vector.crates/vm/src/protocol/object.rs (2)
7-16: LGTM - Import updates align with new construction pathway.The import changes correctly add:
FuncArgsfor constructing function argumentsConstructortrait for invoking the slot_new pathwayThese support the refactored
bytes()method below.
34-43: LGTM - Cleaner construction pathway via Constructor trait.The refactored
bytes()method correctly:
- Maintains the
PyInterror handling (bytes shouldn't accept int directly via this path)- Creates
FuncArgsfrom the single object argument- Delegates to
PyBytes::slot_newwhich handles all construction logic including__bytes__method invocation and optimizationsThis centralizes the bytes construction logic and eliminates the now-removed
get_bytes()pathway.crates/vm/src/builtins/tuple.rs (1)
112-152: LGTM - Constructor follows the unified pattern across builtins.The implementation correctly handles all optimization cases:
- Returns exact input tuple as-is (lines 121-125)
- Returns empty tuple singleton for missing iterable (lines 128-130)
- Returns empty tuple singleton for empty result (lines 139-142)
- Properly separates slot binding (
slot_new) from payload creation (py_new)The
type Args = Vec<PyObjectRef>withpy_newacceptingelements: Self::Argsprovides a clean interface whileslot_newhandles theFuncArgstoVecconversion.crates/vm/src/builtins/bytes.rs (2)
94-118: Constructor optimizations look correct and consistent with other builtin types.The optimization pattern correctly mirrors other builtin constructors (tuple, str, float):
- Empty singleton returned for exact type with no arguments
- Exact input bytes returned as-is when no encoding/errors specified
- Use of
downcast_exactproperly ensures only exactPyBytesinstances bypass construction
139-153: Fallback path and simplifiedpy_newlook good.The structure cleanly separates concerns:
slot_newhandles all optimization logic and protocol dispatchpy_newis reduced to simple construction fromVec<u8>- Empty singleton optimization in the fallback path matches the pattern in
tuple.rs
Sorry, something went wrong.
a477835
into
RustPython:main
Dec 11, 2025
Summary by CodeRabbit
✏️ Tip: You can customize this high-level summary in your review settings.