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

change PyAnyMethods::dir to be fallible #4100

Merged
merged 1 commit into from
Apr 19, 2024
Merged
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/4100.changed.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Change `PyAnyMethods::dir` to be fallible and return `PyResult<Bound<'py, PyList>>` (and similar for `PyAny::dir`).
34 changes: 29 additions & 5 deletions src/types/any.rs
Original file line number Diff line number Diff line change
Expand Up @@ -845,8 +845,8 @@ impl PyAny {
/// Returns the list of attributes of this object.
///
/// This is equivalent to the Python expression `dir(self)`.
pub fn dir(&self) -> &PyList {
self.as_borrowed().dir().into_gil_ref()
pub fn dir(&self) -> PyResult<&PyList> {
self.as_borrowed().dir().map(Bound::into_gil_ref)
}

/// Checks whether this object is an instance of type `ty`.
Expand Down Expand Up @@ -1674,7 +1674,7 @@ pub trait PyAnyMethods<'py>: crate::sealed::Sealed {
/// Returns the list of attributes of this object.
///
/// This is equivalent to the Python expression `dir(self)`.
fn dir(&self) -> Bound<'py, PyList>;
fn dir(&self) -> PyResult<Bound<'py, PyList>>;

/// Checks whether this object is an instance of type `ty`.
///
Expand Down Expand Up @@ -2220,10 +2220,10 @@ impl<'py> PyAnyMethods<'py> for Bound<'py, PyAny> {
Ok(v as usize)
}

fn dir(&self) -> Bound<'py, PyList> {
fn dir(&self) -> PyResult<Bound<'py, PyList>> {
unsafe {
ffi::PyObject_Dir(self.as_ptr())
.assume_owned(self.py())
.assume_owned_or_err(self.py())
.downcast_into_unchecked()
}
}
Expand Down Expand Up @@ -2471,6 +2471,7 @@ class SimpleClass:
.unwrap();
let a = obj
.dir()
.unwrap()
.into_iter()
.map(|x| x.extract::<String>().unwrap());
let b = dir.into_iter().map(|x| x.extract::<String>().unwrap());
Expand Down Expand Up @@ -2745,4 +2746,27 @@ class SimpleClass:
assert!(not_container.is_empty().is_err());
});
}

#[cfg(feature = "macros")]
#[test]
#[allow(unknown_lints, non_local_definitions)]
fn test_fallible_dir() {
use crate::exceptions::PyValueError;
use crate::prelude::*;

#[pyclass(crate = "crate")]
struct DirFail;

#[pymethods(crate = "crate")]
impl DirFail {
fn __dir__(&self) -> PyResult<PyObject> {
Err(PyValueError::new_err("uh-oh!"))
}
}

Python::with_gil(|py| {
let obj = Bound::new(py, DirFail).unwrap();
assert!(obj.dir().unwrap_err().is_instance_of::<PyValueError>(py));
})
}
}
Loading