From ced6b682bf0f27243cc0eff4f5ca5634f2c71125 Mon Sep 17 00:00:00 2001 From: ChJR Date: Mon, 13 Jun 2022 01:19:23 +0900 Subject: [PATCH] Fix string representations of @classmethod and @staticmethod --- vm/src/builtins/classmethod.rs | 22 +++++++++++++++++++++- vm/src/builtins/staticmethod.rs | 20 ++++++++++++++++++++ 2 files changed, 41 insertions(+), 1 deletion(-) diff --git a/vm/src/builtins/classmethod.rs b/vm/src/builtins/classmethod.rs index 60d33710c..00e67d52e 100644 --- a/vm/src/builtins/classmethod.rs +++ b/vm/src/builtins/classmethod.rs @@ -1,4 +1,4 @@ -use super::{PyBoundMethod, PyType, PyTypeRef}; +use super::{PyBoundMethod, PyStr, PyType, PyTypeRef}; use crate::{ class::PyClassImpl, common::lock::PyMutex, @@ -135,6 +135,26 @@ impl PyClassMethod { self.callable.lock().get_attr("__annotations__", vm) } + #[pymethod(magic)] + fn repr(&self, vm: &VirtualMachine) -> Option { + let callable = self.callable.lock().repr(vm).unwrap(); + let class = Self::class(vm); + + match ( + class + .qualname(vm) + .downcast_ref::() + .map(|n| n.as_str()), + class.module(vm).downcast_ref::().map(|m| m.as_str()), + ) { + (None, _) => None, + (Some(qualname), Some(module)) if module != "builtins" => { + Some(format!("<{}.{}({})>", module, qualname, callable)) + } + _ => Some(format!("<{}({})>", class.slot_name(), callable)), + } + } + #[pyproperty(magic)] fn isabstractmethod(&self, vm: &VirtualMachine) -> PyObjectRef { match vm.get_attribute_opt(self.callable.lock().clone(), "__isabstractmethod__") { diff --git a/vm/src/builtins/staticmethod.rs b/vm/src/builtins/staticmethod.rs index 52d796487..194601156 100644 --- a/vm/src/builtins/staticmethod.rs +++ b/vm/src/builtins/staticmethod.rs @@ -108,6 +108,26 @@ impl PyStaticMethod { self.callable.get_attr("__annotations__", vm) } + #[pymethod(magic)] + fn repr(&self, vm: &VirtualMachine) -> Option { + let callable = self.callable.repr(vm).unwrap(); + let class = Self::class(vm); + + match ( + class + .qualname(vm) + .downcast_ref::() + .map(|n| n.as_str()), + class.module(vm).downcast_ref::().map(|m| m.as_str()), + ) { + (None, _) => None, + (Some(qualname), Some(module)) if module != "builtins" => { + Some(format!("<{}.{}({})>", module, qualname, callable)) + } + _ => Some(format!("<{}({})>", class.slot_name(), callable)), + } + } + #[pyproperty(magic)] fn isabstractmethod(&self, vm: &VirtualMachine) -> PyObjectRef { match vm.get_attribute_opt(self.callable.clone(), "__isabstractmethod__") {