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

Add super object #2486

Merged
merged 9 commits into from Jul 3, 2022
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Expand Up @@ -22,6 +22,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- Add `CompareOp::matches` to easily implement `__richcmp__` as the result of a
Rust `std::cmp::Ordering` comparison. [#2460](https://github.com/PyO3/pyo3/pull/2460)
- Supprt `#[pyo3(name)]` on enum variants [#2457](https://github.com/PyO3/pyo3/pull/2457)
- Add `PySuper` object [#2049](https://github.com/PyO3/pyo3/issues/2049)

### Changed

Expand Down
9 changes: 8 additions & 1 deletion src/types/any.rs
Expand Up @@ -3,7 +3,7 @@ use crate::conversion::{AsPyPointer, FromPyObject, IntoPy, IntoPyPointer, PyTryF
use crate::err::{PyDowncastError, PyErr, PyResult};
use crate::exceptions::PyTypeError;
use crate::type_object::PyTypeInfo;
use crate::types::{PyDict, PyIterator, PyList, PyString, PyTuple, PyType};
use crate::types::{PyDict, PyIterator, PyList, PyString, PySuper, PyTuple, PyType};
use crate::{err, ffi, Py, PyNativeType, PyObject, Python};
use std::cell::UnsafeCell;
use std::cmp::Ordering;
Expand Down Expand Up @@ -883,6 +883,13 @@ impl PyAny {
pub fn py(&self) -> Python<'_> {
PyNativeType::py(self)
}

/// Return a proxy object that delegates method calls to a parent or sibling class of type.
///
/// This is equivalent to the Python expression `super()`
pub fn py_super(&self) -> PyResult<&PySuper> {
PySuper::new(self.py(), self.get_type(), self)
}
}

#[cfg(test)]
Expand Down
2 changes: 2 additions & 0 deletions src/types/mod.rs
Expand Up @@ -27,6 +27,7 @@ pub use self::mapping::PyMapping;
pub use self::module::PyModule;
pub use self::num::PyLong;
pub use self::num::PyLong as PyInt;
pub use self::pysuper::PySuper;
pub use self::sequence::PySequence;
pub use self::set::PySet;
pub use self::slice::{PySlice, PySliceIndices};
Expand Down Expand Up @@ -277,6 +278,7 @@ mod list;
mod mapping;
mod module;
mod num;
mod pysuper;
mod sequence;
mod set;
mod slice;
Expand Down
26 changes: 26 additions & 0 deletions src/types/pysuper.rs
@@ -0,0 +1,26 @@
use crate::ffi;
use crate::type_object::PyTypeInfo;
use crate::types::{PyTuple, PyType};
use crate::{AsPyPointer, Py, PyAny, PyErr, PyResult, Python};

/// Represents a Python `super` object.
///
/// This type is immutable.
#[repr(transparent)]
pub struct PySuper(PyAny);

pyobject_native_type_core!(PySuper, ffi::PySuper_Type, #checkfunction=ffi::PyType_Check);
ikrivosheev marked this conversation as resolved.
Show resolved Hide resolved

impl PySuper {
pub fn new<'py>(py: Python<'py>, ty: &'py PyType, obj: &'py PyAny) -> PyResult<&'py PySuper> {
ikrivosheev marked this conversation as resolved.
Show resolved Hide resolved
ikrivosheev marked this conversation as resolved.
Show resolved Hide resolved
let args = PyTuple::new(py, &[ty, obj]);
let type_ = PySuper::type_object_raw(py);
let super_ = unsafe { ffi::PyObject_CallObject(type_ as *mut _, args.as_ptr()) };
ikrivosheev marked this conversation as resolved.
Show resolved Hide resolved
if let Some(exc) = PyErr::take(py) {
return Err(exc);
}

let super_: PyResult<Py<PySuper>> = unsafe { Py::from_borrowed_ptr_or_err(py, super_) };
super_.map(|o| o.into_ref(py))
}
}
52 changes: 52 additions & 0 deletions tests/test_super.rs
@@ -0,0 +1,52 @@
#![cfg(feature = "macros")]

use pyo3::prelude::*;

#[pyclass(subclass)]
struct BaseClass {
val1: usize,
}

#[pymethods]
impl BaseClass {
#[new]
fn new() -> Self {
BaseClass { val1: 10 }
}

pub fn method1(&self) -> usize {
self.val1
}
}

#[pyclass(extends=BaseClass)]
struct SubClass {}

#[pymethods]
impl SubClass {
#[new]
fn new() -> (Self, BaseClass) {
(SubClass {}, BaseClass::new())
}

fn method2<'a>(self_: PyRef<'_, Self>, py: Python<'a>) -> PyResult<&'a PyAny> {
let any: Py<PyAny> = self_.into_py(py);
let super_ = any.into_ref(py).py_super()?;
ikrivosheev marked this conversation as resolved.
Show resolved Hide resolved
super_.call_method("method1", (), None)
ikrivosheev marked this conversation as resolved.
Show resolved Hide resolved
}
}

#[test]
fn test_call_super_method() {
let gil = Python::acquire_gil();
let py = gil.python();
let cls = py.get_type::<SubClass>();
pyo3::py_run!(
py,
cls,
r#"
obj = cls()
assert obj.method2() == 10
"#
)
}