Correct object.__repr__

This commit is contained in:
Lee Dogeon
2021-09-10 16:38:34 +01:00
committed by GitHub
parent 2e685b858a
commit 0d2a4264b3
4 changed files with 26 additions and 15 deletions

View File

@@ -2166,8 +2166,6 @@ class TestRepr(unittest.TestCase):
self.assertEqual(repr(C.D(0)), 'TestRepr.test_repr.<locals>.C.D(i=0)')
self.assertEqual(repr(C.E()), 'TestRepr.test_repr.<locals>.C.E()')
# TODO: RUSTPYTHON
@unittest.expectedFailure
def test_no_repr(self):
# Test a class with no __repr__ and repr=False.
@dataclass(repr=False)

View File

@@ -318,8 +318,6 @@ class bar:
# Module name may be prefixed with "test.", depending on how run.
self.assertEqual(repr(bar.bar), "<class '%s.bar'>" % bar.__name__)
# TODO: RUSTPYTHON
@unittest.expectedFailure
def test_instance(self):
self._check_path_limitations('baz')
write_file(os.path.join(self.subpkgname, 'baz.py'), '''\
@@ -332,8 +330,6 @@ class baz:
self.assertTrue(repr(ibaz).startswith(
"<%s.baz object at 0x" % baz.__name__))
# TODO: RUSTPYTHON
@unittest.expectedFailure
def test_method(self):
self._check_path_limitations('qux')
eq = self.assertEqual

View File

@@ -1,7 +1,7 @@
use super::dict::{PyDict, PyDictRef};
use super::list::PyList;
use super::pybool;
use super::pystr::PyStrRef;
use super::pystr::{PyStr, PyStrRef};
use super::pytype::PyTypeRef;
use crate::builtins::pytype::PyType;
use crate::common::hash::PyHash;
@@ -183,12 +183,29 @@ impl PyBaseObject {
/// Return repr(self).
#[pymethod(magic)]
fn repr(zelf: PyObjectRef) -> String {
format!(
"<{} object at {:#x}>",
zelf.class().tp_name(),
zelf.get_id()
)
fn repr(zelf: PyObjectRef, vm: &VirtualMachine) -> Option<String> {
let class = zelf.class();
match (
class
.qualname(vm)
.downcast_ref::<PyStr>()
.map(|n| n.as_str()),
class.module(vm).downcast_ref::<PyStr>().map(|m| m.as_str()),
) {
(None, _) => None,
(Some(qualname), Some(module)) if module != "builtins" => Some(format!(
"<{}.{} object at {:#x}>",
module,
qualname,
zelf.get_id()
)),
_ => Some(format!(
"<{} object at {:#x}>",
class.tp_name(),
zelf.get_id()
)),
}
}
#[pyclassmethod(magic)]

View File

@@ -313,7 +313,7 @@ impl PyType {
}
#[pyproperty(magic)]
fn qualname(&self, vm: &VirtualMachine) -> PyObjectRef {
pub fn qualname(&self, vm: &VirtualMachine) -> PyObjectRef {
self.attributes
.read()
.get("__qualname__")
@@ -330,7 +330,7 @@ impl PyType {
}
#[pyproperty(magic)]
fn module(&self, vm: &VirtualMachine) -> PyObjectRef {
pub fn module(&self, vm: &VirtualMachine) -> PyObjectRef {
// TODO: Implement getting the actual module a builtin type is from
self.attributes
.read()