Repository navigation
Add explicit Python collection conversion adapters #9372
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
Open
1ndahous3
wants to merge
3
commits into
RustPython:main
Choose a base branch
from
1ndahous3:py_collection_adapters
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+422
−72
Open
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,118 @@ | ||
| use core::{fmt, marker::PhantomData}; | ||
|
|
||
| use crate::{ | ||
| PyObjectRef, PyResult, VirtualMachine, | ||
| builtins::PyDictRef, | ||
| object::{Traverse, TraverseFn}, | ||
| }; | ||
|
|
||
| use super::ToPyObject; | ||
|
|
||
| /// A Python dict constructed from Rust key/value pairs. | ||
| /// | ||
| /// Keys use Python hashing and equality; later equal keys replace earlier values. | ||
| /// Construction can execute Python code and propagates its exceptions. Cloning | ||
| /// this handle shares the same dictionary, including subsequent mutations. | ||
| /// | ||
| /// `K` and `V` describe the input conversion, not runtime invariants: Python can | ||
| /// insert other types. Access through [`Self::as_dict`] is therefore untyped. | ||
| pub struct PyDictOf<K, V> { | ||
| dict: PyDictRef, | ||
| types: PhantomData<fn() -> (K, V)>, | ||
| } | ||
|
|
||
| impl<K: ToPyObject, V: ToPyObject> PyDictOf<K, V> { | ||
| pub fn try_new(items: impl IntoIterator<Item = (K, V)>, vm: &VirtualMachine) -> PyResult<Self> { | ||
| let dict = vm.ctx.new_dict(); | ||
| for (key, value) in items { | ||
| let key = key.to_pyobject(vm); | ||
| let value = value.to_pyobject(vm); | ||
| dict.set_item(&*key, value, vm)?; | ||
| } | ||
| Ok(Self { | ||
| dict, | ||
| types: PhantomData, | ||
| }) | ||
| } | ||
| } | ||
|
|
||
| impl<K, V> PyDictOf<K, V> { | ||
| #[must_use] | ||
| pub fn as_dict(&self) -> &PyDictRef { | ||
| &self.dict | ||
| } | ||
|
|
||
| #[must_use] | ||
| pub fn into_dict(self) -> PyDictRef { | ||
| self.dict | ||
| } | ||
| } | ||
|
|
||
| impl<K, V> Clone for PyDictOf<K, V> { | ||
| fn clone(&self) -> Self { | ||
| Self { | ||
| dict: self.dict.clone(), | ||
| types: PhantomData, | ||
| } | ||
| } | ||
| } | ||
|
|
||
| impl<K, V> fmt::Debug for PyDictOf<K, V> { | ||
| fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { | ||
| self.dict.fmt(f) | ||
| } | ||
| } | ||
|
|
||
| impl<K, V> ToPyObject for PyDictOf<K, V> { | ||
| fn to_pyobject(self, _vm: &VirtualMachine) -> PyObjectRef { | ||
| self.dict.into() | ||
| } | ||
| } | ||
|
|
||
| impl<K, V> From<PyDictOf<K, V>> for PyObjectRef { | ||
| fn from(value: PyDictOf<K, V>) -> Self { | ||
| value.dict.into() | ||
| } | ||
| } | ||
|
|
||
| // SAFETY: Only `dict` owns a Python reference; visit it once without cloning. | ||
| unsafe impl<K, V> Traverse for PyDictOf<K, V> { | ||
| fn traverse(&self, tracer: &mut TraverseFn<'_>) { | ||
| self.dict.traverse(tracer); | ||
| } | ||
| } | ||
|
|
||
| #[cfg(test)] | ||
| mod tests { | ||
| use super::*; | ||
| use crate::{AsObject, Interpreter}; | ||
|
|
||
| #[test] | ||
| fn pairs_use_python_key_semantics_and_propagate_errors() { | ||
| Interpreter::without_stdlib(Default::default()).enter(|vm| { | ||
| let first: PyObjectRef = vm.ctx.new_bool(true).into(); | ||
| let dict = PyDictOf::try_new([(first.clone(), 10), (vm.ctx.new_int(1).into(), 20)], vm) | ||
| .unwrap(); | ||
| let keys = dict.as_dict().keys_vec(); | ||
| assert_eq!(keys.len(), 1); | ||
| assert!(keys[0].is(&first)); | ||
| assert_eq!( | ||
| dict.as_dict() | ||
| .get_item(&*first, vm) | ||
| .unwrap() | ||
| .try_into_value::<i32>(vm) | ||
| .unwrap(), | ||
| 20 | ||
| ); | ||
| assert!(dict.clone().to_pyobject(vm).is(dict.as_dict())); | ||
| let mut visits = 0; | ||
| dict.traverse(&mut |obj| { | ||
| assert!(obj.is(dict.as_dict())); | ||
| visits += 1; | ||
| }); | ||
| assert_eq!(visits, 1); | ||
| let error = PyDictOf::try_new([(vm.ctx.new_list(vec![]), 1)], vm).unwrap_err(); | ||
| assert!(error.fast_isinstance(vm.ctx.exceptions.type_error)); | ||
| }); | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,134 @@ | ||
| use core::{fmt, marker::PhantomData}; | ||
|
|
||
| use crate::{ | ||
| PyObjectRef, VirtualMachine, | ||
| builtins::PyListRef, | ||
| object::{Traverse, TraverseFn}, | ||
| }; | ||
|
|
||
| use super::ToPyObject; | ||
|
|
||
| /// A Python list constructed from Rust values of type `T`. | ||
| /// | ||
| /// Unlike `Vec<u8>`, which converts to Python `bytes`, `PyListOf<u8>` produces | ||
| /// a list of integers. Construction converts each element once; cloning this | ||
| /// handle shares the same Python list, including subsequent mutations. | ||
| /// | ||
| /// `T` describes the input conversion, not a runtime invariant: Python can add | ||
| /// objects of any type. Access through [`Self::as_list`] is therefore untyped. | ||
| pub struct PyListOf<T> { | ||
| list: PyListRef, | ||
| element: PhantomData<fn() -> T>, | ||
| } | ||
|
|
||
| impl<T: ToPyObject> PyListOf<T> { | ||
| pub fn new(items: impl IntoIterator<Item = T>, vm: &VirtualMachine) -> Self { | ||
| Self { | ||
| list: vm | ||
| .ctx | ||
| .new_list(items.into_iter().map(|item| item.to_pyobject(vm)).collect()), | ||
| element: PhantomData, | ||
| } | ||
| } | ||
| } | ||
|
|
||
| impl<T> PyListOf<T> { | ||
| #[must_use] | ||
| pub fn as_list(&self) -> &PyListRef { | ||
| &self.list | ||
| } | ||
|
|
||
| #[must_use] | ||
| pub fn into_list(self) -> PyListRef { | ||
| self.list | ||
| } | ||
| } | ||
|
|
||
| impl<T> Clone for PyListOf<T> { | ||
| fn clone(&self) -> Self { | ||
| Self { | ||
| list: self.list.clone(), | ||
| element: PhantomData, | ||
| } | ||
| } | ||
| } | ||
|
|
||
| impl<T> fmt::Debug for PyListOf<T> { | ||
| fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { | ||
| self.list.fmt(f) | ||
| } | ||
| } | ||
|
|
||
| impl<T> ToPyObject for PyListOf<T> { | ||
| fn to_pyobject(self, _vm: &VirtualMachine) -> PyObjectRef { | ||
| self.list.into() | ||
| } | ||
| } | ||
|
|
||
| impl<T> From<PyListOf<T>> for PyObjectRef { | ||
| fn from(value: PyListOf<T>) -> Self { | ||
| value.list.into() | ||
| } | ||
| } | ||
|
|
||
| // SAFETY: Only `list` owns a Python reference; visit it once without cloning. | ||
| unsafe impl<T> Traverse for PyListOf<T> { | ||
| fn traverse(&self, tracer: &mut TraverseFn<'_>) { | ||
| self.list.traverse(tracer); | ||
| } | ||
| } | ||
|
|
||
| #[cfg(test)] | ||
| mod tests { | ||
| use super::*; | ||
| use crate::{AsObject, Interpreter, builtins::PyBytes}; | ||
|
|
||
| #[test] | ||
| fn explicit_list_conversion() { | ||
| Interpreter::without_stdlib(Default::default()).enter(|vm| { | ||
| let list = PyListOf::new([0_u8, 255].into_iter().filter(|_| true), vm); | ||
| assert_eq!( | ||
| list.as_list() | ||
| .as_object() | ||
| .try_to_value::<Vec<u8>>(vm) | ||
| .unwrap(), | ||
| [0, 255] | ||
| ); | ||
| assert!( | ||
| vec![0_u8, 255] | ||
| .to_pyobject(vm) | ||
| .downcast_ref::<PyBytes>() | ||
| .is_some() | ||
| ); | ||
| assert!( | ||
| PyListOf::<u8>::new([], vm) | ||
| .as_list() | ||
| .borrow_vec() | ||
| .is_empty() | ||
| ); | ||
| }); | ||
| } | ||
|
|
||
| #[test] | ||
| fn shared_identity_and_traversal_do_not_require_element_traits() { | ||
| struct Item; | ||
| impl ToPyObject for Item { | ||
| fn to_pyobject(self, vm: &VirtualMachine) -> PyObjectRef { | ||
| vm.ctx.new_int(1).into() | ||
| } | ||
| } | ||
| Interpreter::without_stdlib(Default::default()).enter(|vm| { | ||
| let list = PyListOf::new([Item], vm); | ||
| let copy = list.clone(); | ||
| list.as_list().borrow_vec_mut().push(vm.ctx.none()); | ||
| assert_eq!(copy.as_list().borrow_vec().len(), 2); | ||
| let mut visits = 0; | ||
| copy.traverse(&mut |obj| { | ||
| assert!(obj.is(list.as_list())); | ||
| visits += 1; | ||
| }); | ||
| assert_eq!(visits, 1); | ||
| assert!(copy.to_pyobject(vm).is(&list.into_list())); | ||
| }); | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,9 +1,15 @@ | ||
| mod dict; | ||
| mod into_object; | ||
| mod list; | ||
| mod set; | ||
| mod to_pyobject; | ||
| mod transmute_from; | ||
| mod try_from; | ||
|
|
||
| pub use dict::PyDictOf; | ||
| pub use into_object::IntoObject; | ||
| pub use list::PyListOf; | ||
| pub use set::PySetOf; | ||
| pub use to_pyobject::{IntoPyException, ToPyException, ToPyObject, ToPyResult}; | ||
| pub use transmute_from::TransmuteFromObject; | ||
| pub use try_from::{TryFromBorrowedObject, TryFromObject}; |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.