Skip to content

Commit ced6b68

Browse files
committed
Fix string representations of @classmethod and @staticmethod
1 parent 4c97056 commit ced6b68

File tree

2 files changed

+41
-1
lines changed

2 files changed

+41
-1
lines changed

vm/src/builtins/classmethod.rs

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
use super::{PyBoundMethod, PyType, PyTypeRef};
1+
use super::{PyBoundMethod, PyStr, PyType, PyTypeRef};
22
use crate::{
33
class::PyClassImpl,
44
common::lock::PyMutex,
@@ -135,6 +135,26 @@ impl PyClassMethod {
135135
self.callable.lock().get_attr("__annotations__", vm)
136136
}
137137

138+
#[pymethod(magic)]
139+
fn repr(&self, vm: &VirtualMachine) -> Option<String> {
140+
let callable = self.callable.lock().repr(vm).unwrap();
141+
let class = Self::class(vm);
142+
143+
match (
144+
class
145+
.qualname(vm)
146+
.downcast_ref::<PyStr>()
147+
.map(|n| n.as_str()),
148+
class.module(vm).downcast_ref::<PyStr>().map(|m| m.as_str()),
149+
) {
150+
(None, _) => None,
151+
(Some(qualname), Some(module)) if module != "builtins" => {
152+
Some(format!("<{}.{}({})>", module, qualname, callable))
153+
}
154+
_ => Some(format!("<{}({})>", class.slot_name(), callable)),
155+
}
156+
}
157+
138158
#[pyproperty(magic)]
139159
fn isabstractmethod(&self, vm: &VirtualMachine) -> PyObjectRef {
140160
match vm.get_attribute_opt(self.callable.lock().clone(), "__isabstractmethod__") {

vm/src/builtins/staticmethod.rs

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -108,6 +108,26 @@ impl PyStaticMethod {
108108
self.callable.get_attr("__annotations__", vm)
109109
}
110110

111+
#[pymethod(magic)]
112+
fn repr(&self, vm: &VirtualMachine) -> Option<String> {
113+
let callable = self.callable.repr(vm).unwrap();
114+
let class = Self::class(vm);
115+
116+
match (
117+
class
118+
.qualname(vm)
119+
.downcast_ref::<PyStr>()
120+
.map(|n| n.as_str()),
121+
class.module(vm).downcast_ref::<PyStr>().map(|m| m.as_str()),
122+
) {
123+
(None, _) => None,
124+
(Some(qualname), Some(module)) if module != "builtins" => {
125+
Some(format!("<{}.{}({})>", module, qualname, callable))
126+
}
127+
_ => Some(format!("<{}({})>", class.slot_name(), callable)),
128+
}
129+
}
130+
111131
#[pyproperty(magic)]
112132
fn isabstractmethod(&self, vm: &VirtualMachine) -> PyObjectRef {
113133
match vm.get_attribute_opt(self.callable.clone(), "__isabstractmethod__") {

0 commit comments

Comments
 (0)