Fix number __format__ (#6930)

This commit is contained in:
Jeong, YunWon
2026-02-01 17:17:09 +09:00
committed by GitHub
parent 0546bb0410
commit 25bf682006
4 changed files with 18 additions and 7 deletions

View File

@@ -4162,7 +4162,6 @@ class OldTestIntFlag(unittest.TestCase):
self.assertEqual(str(NoName.ONE & NoName.TWO), 'NoName(0)')
self.assertEqual(str(NoName(0)), 'NoName(0)')
@unittest.expectedFailure # TODO: RUSTPYTHON; format(NewPerm.R) does not use __str__
def test_format(self):
Perm = self.Perm
self.assertEqual(format(Perm.R, ''), '4')

View File

@@ -276,9 +276,13 @@ impl PyComplex {
}
#[pymethod]
fn __format__(&self, spec: PyStrRef, vm: &VirtualMachine) -> PyResult<String> {
fn __format__(zelf: &Py<Self>, spec: PyStrRef, vm: &VirtualMachine) -> PyResult<String> {
// Empty format spec: equivalent to str(self)
if spec.is_empty() {
return Ok(zelf.as_object().str(vm)?.as_str().to_owned());
}
FormatSpec::parse(spec.as_str())
.and_then(|format_spec| format_spec.format_complex(&self.value))
.and_then(|format_spec| format_spec.format_complex(&zelf.value))
.map_err(|err| err.into_pyexception(vm))
}
}

View File

@@ -214,9 +214,13 @@ fn float_from_string(val: PyObjectRef, vm: &VirtualMachine) -> PyResult<f64> {
)]
impl PyFloat {
#[pymethod]
fn __format__(&self, spec: PyStrRef, vm: &VirtualMachine) -> PyResult<String> {
fn __format__(zelf: &Py<Self>, spec: PyStrRef, vm: &VirtualMachine) -> PyResult<String> {
// Empty format spec: equivalent to str(self)
if spec.is_empty() {
return Ok(zelf.as_object().str(vm)?.as_str().to_owned());
}
FormatSpec::parse(spec.as_str())
.and_then(|format_spec| format_spec.format_float(self.value))
.and_then(|format_spec| format_spec.format_float(zelf.value))
.map_err(|err| err.into_pyexception(vm))
}

View File

@@ -444,9 +444,13 @@ impl PyInt {
}
#[pymethod]
fn __format__(&self, spec: PyStrRef, vm: &VirtualMachine) -> PyResult<String> {
fn __format__(zelf: &Py<Self>, spec: PyStrRef, vm: &VirtualMachine) -> PyResult<String> {
// Empty format spec on a subclass: equivalent to str(self)
if spec.is_empty() && !zelf.class().is(vm.ctx.types.int_type) {
return Ok(zelf.as_object().str(vm)?.as_str().to_owned());
}
FormatSpec::parse(spec.as_str())
.and_then(|format_spec| format_spec.format_int(&self.value))
.and_then(|format_spec| format_spec.format_int(&zelf.value))
.map_err(|err| err.into_pyexception(vm))
}