Skip to content

Commit

Permalink
dict and list bound constructors
Browse files Browse the repository at this point in the history
  • Loading branch information
davidhewitt committed Jan 16, 2024
1 parent 0b9dd26 commit 1df1c10
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 6 deletions.
9 changes: 7 additions & 2 deletions src/types/dict.rs
Original file line number Diff line number Diff line change
Expand Up @@ -56,9 +56,14 @@ pyobject_native_type_core!(
);

impl PyDict {
/// Creates a new empty dictionary.
/// Deprecated form of [`PyDict::new_bound`].
pub fn new(py: Python<'_>) -> &PyDict {
unsafe { py.from_owned_ptr(ffi::PyDict_New()) }
Self::new_bound(py).into_gil_ref()
}

/// Creates a new empty dictionary.
pub fn new_bound(py: Python<'_>) -> Bound<'_, PyDict> {
unsafe { ffi::PyDict_New().assume_owned(py).downcast_into_unchecked() }
}

/// Creates a new dictionary from the sequence given.
Expand Down
29 changes: 25 additions & 4 deletions src/types/list.rs
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,15 @@ pub(crate) fn new_from_iter<'py>(
}

impl PyList {
/// Deprecated form of [`PyList::new_bound`].
pub fn new<T, U>(py: Python<'_>, elements: impl IntoIterator<Item = T, IntoIter = U>) -> &PyList
where
T: ToPyObject,
U: ExactSizeIterator<Item = T>,
{
Self::new_bound(py, elements).into_gil_ref()
}

/// Constructs a new list with the given elements.
///
/// If you want to create a [`PyList`] with elements of different or unknown types, or from an
Expand All @@ -82,18 +91,30 @@ impl PyList {
/// All standard library structures implement this trait correctly, if they do, so calling this
/// function with (for example) [`Vec`]`<T>` or `&[T]` will always succeed.
#[track_caller]
pub fn new<T, U>(py: Python<'_>, elements: impl IntoIterator<Item = T, IntoIter = U>) -> &PyList
pub fn new_bound<T, U>(
py: Python<'_>,
elements: impl IntoIterator<Item = T, IntoIter = U>,
) -> Bound<'_, PyList>
where
T: ToPyObject,
U: ExactSizeIterator<Item = T>,
{
let mut iter = elements.into_iter().map(|e| e.to_object(py));
new_from_iter(py, &mut iter).into_gil_ref()
new_from_iter(py, &mut iter)
}

/// Constructs a new empty list.
/// Deprecated form of [`PyList::empty_bound`].
pub fn empty(py: Python<'_>) -> &PyList {
unsafe { py.from_owned_ptr(ffi::PyList_New(0)) }
Self::empty_bound(py).into_gil_ref()
}

/// Constructs a new empty list.
pub fn empty_bound(py: Python<'_>) -> Bound<'_, PyList> {
unsafe {
ffi::PyList_New(0)
.assume_owned(py)
.downcast_into_unchecked()
}
}

/// Returns the length of the list.
Expand Down

0 comments on commit 1df1c10

Please sign in to comment.