Skip to content
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

Implement ToPyObject for Box<T> #3729

Closed
wants to merge 4 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions newsfragments/3729.added.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Implement `IntoPy<PyObject>` and `ToPyObject` for `Box<T>`.
35 changes: 34 additions & 1 deletion src/conversion.rs
Original file line number Diff line number Diff line change
Expand Up @@ -243,6 +243,21 @@ impl<T: ?Sized + ToPyObject> ToPyObject for &'_ T {
}
}

impl<T: ?Sized + ToPyObject> ToPyObject for Box<T> {
fn to_object(&self, py: Python<'_>) -> PyObject {
self.as_ref().to_object(py)
}
}

impl<T: ?Sized> IntoPy<PyObject> for Box<T>
where
T: IntoPy<PyObject>,
{
fn into_py(self, py: Python<'_>) -> PyObject {
(*self).into_py(py)
}
}

/// `Option::Some<T>` is converted like `T`.
/// `Option::None` is converted to Python `None`.
impl<T> ToPyObject for Option<T>
Expand Down Expand Up @@ -578,7 +593,7 @@ mod test_no_clone {}

#[cfg(test)]
mod tests {
use crate::{PyObject, Python};
use crate::{IntoPy, PyObject, Python, ToPyObject};

#[allow(deprecated)]
mod deprecated {
Expand Down Expand Up @@ -641,4 +656,22 @@ mod tests {
assert_eq!(none.get_refcnt(), ref_cnt);
});
}

#[test]
fn test_box_topyobject() {
let s: Box<str> = "test".into();

let obj = Python::with_gil(|py| s.to_object(py));

assert_eq!(&obj.to_string(), "test")
}

#[test]
fn test_box_intopy() {
let s: Box<str> = "test".into();

let obj: PyObject = Python::with_gil(|py| s.into_py(py));
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The fact that I need to specifically annotate the type of obj here makes me suspicious that implementing IntoPy like above is doing something funky.


assert_eq!(&obj.to_string(), "test")
}
}
Loading