From 591cdb0bf83d5c5fd024c57db2fe4b33000dc1fc Mon Sep 17 00:00:00 2001 From: David Hewitt Date: Fri, 14 Jun 2024 20:08:35 +0100 Subject: [PATCH] implement `PyModuleMethods::filename` on PyPy (#4249) --- newsfragments/4249.added.md | 1 + src/types/module.rs | 14 ++++++++++---- 2 files changed, 11 insertions(+), 4 deletions(-) create mode 100644 newsfragments/4249.added.md diff --git a/newsfragments/4249.added.md b/newsfragments/4249.added.md new file mode 100644 index 00000000..8037f562 --- /dev/null +++ b/newsfragments/4249.added.md @@ -0,0 +1 @@ +Implement `PyModuleMethods::filename` on PyPy. diff --git a/src/types/module.rs b/src/types/module.rs index f0ae7385..20f8305a 100644 --- a/src/types/module.rs +++ b/src/types/module.rs @@ -220,7 +220,6 @@ impl PyModule { /// Returns the filename (the `__file__` attribute) of the module. /// /// May fail if the module does not have a `__file__` attribute. - #[cfg(not(PyPy))] pub fn filename(&self) -> PyResult<&str> { self.as_borrowed().filename()?.into_gil_ref().to_str() } @@ -429,7 +428,6 @@ pub trait PyModuleMethods<'py>: crate::sealed::Sealed { /// Returns the filename (the `__file__` attribute) of the module. /// /// May fail if the module does not have a `__file__` attribute. - #[cfg(not(PyPy))] fn filename(&self) -> PyResult>; /// Adds an attribute to the module. @@ -644,13 +642,22 @@ impl<'py> PyModuleMethods<'py> for Bound<'py, PyModule> { } } - #[cfg(not(PyPy))] fn filename(&self) -> PyResult> { + #[cfg(not(PyPy))] unsafe { ffi::PyModule_GetFilenameObject(self.as_ptr()) .assume_owned_or_err(self.py()) .downcast_into_unchecked() } + + #[cfg(PyPy)] + { + self.dict() + .get_item("__file__") + .map_err(|_| exceptions::PyAttributeError::new_err("__file__"))? + .downcast_into() + .map_err(PyErr::from) + } } fn add(&self, name: N, value: V) -> PyResult<()> @@ -737,7 +744,6 @@ mod tests { } #[test] - #[cfg(not(PyPy))] fn module_filename() { Python::with_gil(|py| { let site = PyModule::import_bound(py, "site").unwrap();