Skip to content

Complete tp_repr #5852

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

Merged
merged 1 commit into from
Jun 27, 2025
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
18 changes: 12 additions & 6 deletions vm/src/protocol/object.rs
Original file line number Diff line number Diff line change
Expand Up @@ -330,12 +330,18 @@ impl PyObject {

pub fn repr(&self, vm: &VirtualMachine) -> PyResult<PyStrRef> {
vm.with_recursion("while getting the repr of an object", || {
match self.class().slots.repr.load() {
Some(slot) => slot(self, vm),
None => vm
.call_special_method(self, identifier!(vm, __repr__), ())?
.try_into_value(vm), // TODO: remove magic method call once __repr__ is fully ported to slot
}
// TODO: RustPython does not implement type slots inheritance yet
self.class()
.mro_find_map(|cls| cls.slots.repr.load())
.map_or_else(
|| {
Err(vm.new_runtime_error(format!(
"BUG: object of type '{}' has no __repr__ method. This is a bug in RustPython.",
self.class().name()
)))
},
|repr| repr(self, vm),
)
})
}

Expand Down
53 changes: 31 additions & 22 deletions vm/src/types/structseq.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use crate::{
AsObject, Py, PyObjectRef, PyPayload, PyRef, PyResult, VirtualMachine,
builtins::{PyBaseExceptionRef, PyTuple, PyTupleRef, PyType},
AsObject, Py, PyObject, PyObjectRef, PyPayload, PyRef, PyResult, VirtualMachine,
builtins::{PyBaseExceptionRef, PyStrRef, PyTuple, PyTupleRef, PyType},
class::{PyClassImpl, StaticType},
vm::Context,
};
Expand Down Expand Up @@ -47,31 +47,40 @@ pub trait PyStructSequence: StaticType + PyClassImpl + Sized + 'static {
Ok(seq)
}

#[pymethod]
fn __repr__(zelf: PyRef<PyTuple>, vm: &VirtualMachine) -> PyResult<String> {
#[pyslot]
fn slot_repr(zelf: &PyObject, vm: &VirtualMachine) -> PyResult<PyStrRef> {
let zelf = zelf
.downcast_ref::<PyTuple>()
.ok_or_else(|| vm.new_type_error("unexpected payload for __repr__"))?;

let format_field = |(value, name): (&PyObjectRef, _)| {
let s = value.repr(vm)?;
Ok(format!("{name}={s}"))
};
let (body, suffix) = if let Some(_guard) =
rustpython_vm::recursion::ReprGuard::enter(vm, zelf.as_object())
{
if Self::REQUIRED_FIELD_NAMES.len() == 1 {
let value = zelf.first().unwrap();
let formatted = format_field((value, Self::REQUIRED_FIELD_NAMES[0]))?;
(formatted, ",")
let (body, suffix) =
if let Some(_guard) = rustpython_vm::recursion::ReprGuard::enter(vm, zelf.as_ref()) {
if Self::REQUIRED_FIELD_NAMES.len() == 1 {
let value = zelf.first().unwrap();
let formatted = format_field((value, Self::REQUIRED_FIELD_NAMES[0]))?;
(formatted, ",")
} else {
let fields: PyResult<Vec<_>> = zelf
.iter()
.zip(Self::REQUIRED_FIELD_NAMES.iter().copied())
.map(format_field)
.collect();
(fields?.join(", "), "")
}
} else {
let fields: PyResult<Vec<_>> = zelf
.iter()
.zip(Self::REQUIRED_FIELD_NAMES.iter().copied())
.map(format_field)
.collect();
(fields?.join(", "), "")
}
} else {
(String::new(), "...")
};
Ok(format!("{}({}{})", Self::TP_NAME, body, suffix))
(String::new(), "...")
};
let repr_str = format!("{}({}{})", Self::TP_NAME, body, suffix);
Ok(vm.ctx.new_str(repr_str))
}

#[pymethod]
fn __repr__(zelf: PyObjectRef, vm: &VirtualMachine) -> PyResult<PyStrRef> {
Self::slot_repr(&zelf, vm)
}

#[pymethod]
Expand Down
Loading