Skip to content

Commit

Permalink
Convert PathBuf into python pathlib.Path
Browse files Browse the repository at this point in the history
  • Loading branch information
bschoenmaeckers committed Feb 20, 2025
1 parent 73ce403 commit fc26584
Show file tree
Hide file tree
Showing 4 changed files with 39 additions and 29 deletions.
1 change: 1 addition & 0 deletions newsfragments/4925.changed.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Convert `PathBuf` & `Path` into python `pathlib.Path` instead of `PyString`
8 changes: 4 additions & 4 deletions pytests/tests/test_path.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,21 +7,21 @@

def test_make_path():
p = rpath.make_path()
assert p == "/root"
assert p == pathlib.Path("/root")


def test_take_pathbuf():
p = "/root"
assert rpath.take_pathbuf(p) == p
assert rpath.take_pathbuf(p) == pathlib.Path(p)


def test_take_pathlib():
p = pathlib.Path("/root")
assert rpath.take_pathbuf(p) == str(p)
assert rpath.take_pathbuf(p) == p


def test_take_pathlike():
assert rpath.take_pathbuf(PathLike("/root")) == "/root"
assert rpath.take_pathbuf(PathLike("/root")) == pathlib.Path("/root")


def test_take_invalid_pathlike():
Expand Down
57 changes: 33 additions & 24 deletions src/conversions/std/path.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,12 @@
use crate::conversion::IntoPyObject;
use crate::ffi_ptr_ext::FfiPtrExt;
use crate::instance::Bound;
use crate::sync::GILOnceCell;
use crate::types::any::PyAnyMethods;
use crate::types::PyString;
use crate::{ffi, FromPyObject, PyAny, PyObject, PyResult, Python};
use crate::{ffi, FromPyObject, PyAny, PyErr, PyObject, PyResult, Python};
#[allow(deprecated)]
use crate::{IntoPy, ToPyObject};
use std::borrow::Cow;
use std::convert::Infallible;
use std::ffi::OsString;
use std::path::{Path, PathBuf};

Expand Down Expand Up @@ -38,20 +37,23 @@ impl IntoPy<PyObject> for &Path {
}

impl<'py> IntoPyObject<'py> for &Path {
type Target = PyString;
type Target = PyAny;
type Output = Bound<'py, Self::Target>;
type Error = Infallible;
type Error = PyErr;

#[inline]
fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
self.as_os_str().into_pyobject(py)
static PY_PATH: GILOnceCell<PyObject> = GILOnceCell::new();
PY_PATH
.import(py, "pathlib", "Path")?
.call((self.as_os_str(),), None)
}
}

impl<'py> IntoPyObject<'py> for &&Path {
type Target = PyString;
type Target = PyAny;
type Output = Bound<'py, Self::Target>;
type Error = Infallible;
type Error = PyErr;

#[inline]
fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
Expand All @@ -76,24 +78,24 @@ impl IntoPy<PyObject> for Cow<'_, Path> {
}

impl<'py> IntoPyObject<'py> for Cow<'_, Path> {
type Target = PyString;
type Target = PyAny;
type Output = Bound<'py, Self::Target>;
type Error = Infallible;
type Error = PyErr;

#[inline]
fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
self.as_os_str().into_pyobject(py)
(*self).into_pyobject(py)
}
}

impl<'py> IntoPyObject<'py> for &Cow<'_, Path> {
type Target = PyString;
type Target = PyAny;
type Output = Bound<'py, Self::Target>;
type Error = Infallible;
type Error = PyErr;

#[inline]
fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
self.as_os_str().into_pyobject(py)
(&**self).into_pyobject(py)
}
}

Expand All @@ -114,13 +116,13 @@ impl IntoPy<PyObject> for PathBuf {
}

impl<'py> IntoPyObject<'py> for PathBuf {
type Target = PyString;
type Target = PyAny;
type Output = Bound<'py, Self::Target>;
type Error = Infallible;
type Error = PyErr;

#[inline]
fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
self.as_os_str().into_pyobject(py)
(&self).into_pyobject(py)
}
}

Expand All @@ -133,20 +135,21 @@ impl IntoPy<PyObject> for &PathBuf {
}

impl<'py> IntoPyObject<'py> for &PathBuf {
type Target = PyString;
type Target = PyAny;
type Output = Bound<'py, Self::Target>;
type Error = Infallible;
type Error = PyErr;

#[inline]
fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
self.as_os_str().into_pyobject(py)
(&**self).into_pyobject(py)
}
}

#[cfg(test)]
mod tests {
use crate::ffi_ptr_ext::FfiPtrExt;
use crate::types::{PyAnyMethods, PyString, PyStringMethods};
use crate::{BoundObject, IntoPyObject, Python};
use crate::{ffi, IntoPyObject, IntoPyObjectExt, Python};
use std::borrow::Cow;
use std::fmt::Debug;
use std::path::{Path, PathBuf};
Expand Down Expand Up @@ -180,10 +183,16 @@ mod tests {
T: IntoPyObject<'py> + AsRef<Path> + Debug + Clone,
T::Error: Debug,
{
let pyobject = obj.clone().into_pyobject(py).unwrap().into_any();
let pystring = pyobject.as_borrowed().downcast::<PyString>().unwrap();
let pyobject = obj.clone().into_bound_py_any(py).unwrap();
let pystring = unsafe {
ffi::PyOS_FSPath(pyobject.as_ptr())
.assume_owned_or_err(py)
.unwrap()
.downcast_into::<PyString>()
.unwrap()
};
assert_eq!(pystring.to_string_lossy(), obj.as_ref().to_string_lossy());
let roundtripped_obj: PathBuf = pystring.extract().unwrap();
let roundtripped_obj: PathBuf = pyobject.extract().unwrap();
assert_eq!(obj.as_ref(), roundtripped_obj.as_path());
}
let path = Path::new("Hello\0\n🐍");
Expand Down
2 changes: 1 addition & 1 deletion tests/test_datetime_import.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ fn test_bad_datetime_module_panic() {
let sys = py.import("sys").unwrap();
sys.getattr("path")
.unwrap()
.call_method1("insert", (0, tmpdir.path()))
.call_method1("insert", (0, tmpdir.path().as_os_str()))
.unwrap();

// This should panic because the "datetime" module is empty
Expand Down

0 comments on commit fc26584

Please sign in to comment.