Skip to content

Commit a0ee811

Browse files
committed
Add __repr__ __str__ for super
1 parent a90001e commit a0ee811

File tree

1 file changed

+29
-2
lines changed

1 file changed

+29
-2
lines changed

vm/src/obj/objsuper.rs

Lines changed: 29 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@ pub type PySuperRef = PyRef<PySuper>;
2424
pub struct PySuper {
2525
obj: PyObjectRef,
2626
typ: PyObjectRef,
27+
obj_type: PyObjectRef,
2728
}
2829

2930
impl PyValue for PySuper {
@@ -53,9 +54,31 @@ pub fn init(context: &PyContext) {
5354
"__new__" => context.new_rustfunc(super_new),
5455
"__getattribute__" => context.new_rustfunc(super_getattribute),
5556
"__doc__" => context.new_str(super_doc.to_string()),
57+
"__str__" => context.new_rustfunc(super_str),
58+
"__repr__" => context.new_rustfunc(super_repr),
5659
});
5760
}
5861

62+
fn super_str(zelf: PyObjectRef, vm: &VirtualMachine) -> PyResult {
63+
vm.call_method(&zelf, "__repr__", vec![])
64+
}
65+
66+
fn super_repr(zelf: PyObjectRef, _vm: &VirtualMachine) -> String {
67+
let super_obj = zelf.downcast::<PySuper>().unwrap();
68+
let class_type_str = if let Ok(type_class) = super_obj.typ.clone().downcast::<PyClass>() {
69+
type_class.name.clone()
70+
} else {
71+
"NONE".to_string()
72+
};
73+
match super_obj.obj_type.clone().downcast::<PyClass>() {
74+
Ok(obj_class_typ) => format!(
75+
"<super: <class '{}'>, <{} object>>",
76+
class_type_str, obj_class_typ.name
77+
),
78+
_ => format!("<super: <class '{}'> NULL>", class_type_str),
79+
}
80+
}
81+
5982
fn super_getattribute(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult {
6083
arg_check!(
6184
vm,
@@ -141,7 +164,7 @@ fn super_new(
141164
};
142165

143166
// Check obj type:
144-
if !objtype::isinstance(&py_obj, &py_type) {
167+
let obj_type = if !objtype::isinstance(&py_obj, &py_type) {
145168
let is_subclass = if let Ok(py_obj) = PyClassRef::try_from_object(vm, py_obj.clone()) {
146169
objtype::issubclass(&py_obj, &py_type)
147170
} else {
@@ -152,11 +175,15 @@ fn super_new(
152175
"super(type, obj): obj must be an instance or subtype of type".to_string(),
153176
));
154177
}
155-
}
178+
PyClassRef::try_from_object(vm, py_obj.clone())?
179+
} else {
180+
py_obj.class()
181+
};
156182

157183
PySuper {
158184
obj: py_obj,
159185
typ: py_type.into_object(),
186+
obj_type: obj_type.into_object(),
160187
}
161188
.into_ref_with_type(vm, cls)
162189
}

0 commit comments

Comments
 (0)