Skip to content

Commit 0f07cf8

Browse files
authored
Merge pull request #886 from fusion-engineering-forks/dir
Add dir() to ObjectProtocol.
2 parents 879b0b5 + d32c3c0 commit 0f07cf8

File tree

2 files changed

+27
-1
lines changed

2 files changed

+27
-1
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.
1818
### Added
1919
* `_PyDict_NewPresized`. [#849](https://github.com/PyO3/pyo3/pull/849)
2020
* `IntoPy<PyObject>` for `HashSet` and `BTreeSet`. [#864](https://github.com/PyO3/pyo3/pull/864)
21+
* `ObjectProtocol::dir`. [#886](https://github.com/PyO3/pyo3/pull/886)
2122

2223
### Fixed
2324
* `__radd__` and other `__r*__` methods now correctly work with operators. [#839](https://github.com/PyO3/pyo3/pull/839)

src/objectprotocol.rs

Lines changed: 26 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
use crate::class::basic::CompareOp;
44
use crate::err::{self, PyDowncastError, PyErr, PyResult};
55
use crate::exceptions::TypeError;
6-
use crate::types::{PyAny, PyDict, PyIterator, PyString, PyTuple, PyType};
6+
use crate::types::{PyAny, PyDict, PyIterator, PyList, PyString, PyTuple, PyType};
77
use crate::{
88
ffi, AsPyPointer, FromPyObject, IntoPy, IntoPyPointer, Py, PyNativeType, PyObject, PyTryFrom,
99
Python, ToBorrowedObject, ToPyObject,
@@ -212,6 +212,9 @@ pub trait ObjectProtocol {
212212
/// Returns the reference count for the Python object.
213213
fn get_refcnt(&self) -> isize;
214214

215+
/// Returns the list of attributes of this object.
216+
fn dir(&self) -> &PyList;
217+
215218
/// Gets the Python builtin value `None`.
216219
#[allow(non_snake_case)] // the Python keyword starts with uppercase
217220
fn None(&self) -> PyObject;
@@ -485,6 +488,10 @@ where
485488
unsafe { ffi::Py_REFCNT(self.as_ptr()) }
486489
}
487490

491+
fn dir(&self) -> &PyList {
492+
unsafe { self.py().from_owned_ptr(ffi::PyObject_Dir(self.as_ptr())) }
493+
}
494+
488495
#[allow(non_snake_case)] // the Python keyword starts with uppercase
489496
fn None(&self) -> PyObject {
490497
unsafe { PyObject::from_borrowed_ptr(self.py(), ffi::Py_None()) }
@@ -545,4 +552,22 @@ mod test {
545552
let obj = py.eval("42", None, None).unwrap();
546553
assert_eq!(unsafe { obj.get_type().as_type_ptr() }, obj.get_type_ptr())
547554
}
555+
556+
#[test]
557+
fn test_dir() {
558+
let gil = Python::acquire_gil();
559+
let py = gil.python();
560+
let obj = py.eval("42", None, None).unwrap();
561+
let dir = py
562+
.eval("dir(42)", None, None)
563+
.unwrap()
564+
.extract::<&PyList>()
565+
.unwrap();
566+
let a = obj
567+
.dir()
568+
.into_iter()
569+
.map(|x| x.extract::<String>().unwrap());
570+
let b = dir.into_iter().map(|x| x.extract::<String>().unwrap());
571+
assert!(a.eq(b));
572+
}
548573
}

0 commit comments

Comments
 (0)