implement `PyModuleMethods::filename` on PyPy (#4249)

This commit is contained in:
David Hewitt 2024-06-14 20:08:35 +01:00 committed by GitHub
parent 5749a08b63
commit 591cdb0bf8
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 11 additions and 4 deletions

View File

@ -0,0 +1 @@
Implement `PyModuleMethods::filename` on PyPy.

View File

@ -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<Bound<'py, PyString>>;
/// 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<Bound<'py, PyString>> {
#[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<N, V>(&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();