From aae82422faf285b8311e412bac1b1d9cbcca13f2 Mon Sep 17 00:00:00 2001 From: Dean Li Date: Thu, 13 May 2021 21:39:13 +0800 Subject: [PATCH] os: implement `repr` for `DirEntry` --- Lib/test/test_os.py | 2 -- vm/src/stdlib/os.rs | 29 ++++++++++++++++++++++++++++- 2 files changed, 28 insertions(+), 3 deletions(-) diff --git a/Lib/test/test_os.py b/Lib/test/test_os.py index fa8398ba1..c2b6e4991 100644 --- a/Lib/test/test_os.py +++ b/Lib/test/test_os.py @@ -3853,8 +3853,6 @@ class TestScandir(unittest.TestCase): finally: os.chdir(old_dir) - # TODO: RUSTPYTHON - @unittest.expectedFailure def test_repr(self): entry = self.create_file_entry() self.assertEqual(repr(entry), "") diff --git a/vm/src/stdlib/os.rs b/vm/src/stdlib/os.rs index 5348c23e5..65c154a22 100644 --- a/vm/src/stdlib/os.rs +++ b/vm/src/stdlib/os.rs @@ -28,7 +28,7 @@ use crate::pyobject::{ PyStructSequence, PyValue, StaticType, TryFromObject, TypeProtocol, }; use crate::slots::PyIter; -use crate::vm::VirtualMachine; +use crate::vm::{ReprGuard, VirtualMachine}; #[cfg(unix)] use std::os::unix::ffi as ffi_ext; @@ -830,6 +830,33 @@ mod _os { fn fspath(&self, vm: &VirtualMachine) -> PyResult { self.path(vm) } + + #[pymethod(magic)] + fn repr(zelf: PyObjectRef, vm: &VirtualMachine) -> PyResult { + let name = match vm.get_attribute(zelf.clone(), "name") { + Ok(name) => Some(name), + Err(e) + if e.isinstance(&vm.ctx.exceptions.attribute_error) + || e.isinstance(&vm.ctx.exceptions.value_error) => + { + None + } + Err(e) => return Err(e), + }; + if let Some(name) = name { + if let Some(_guard) = ReprGuard::enter(vm, &zelf) { + let repr = vm.to_repr(&name)?; + Ok(format!("<{} {}>", zelf.class(), repr)) + } else { + Err(vm.new_runtime_error(format!( + "reentrant call inside {}.__repr__", + zelf.class() + ))) + } + } else { + Ok(format!("<{}>", zelf.class())) + } + } } #[pyattr]