mirror of
https://github.com/RustPython/RustPython.git
synced 2026-06-02 19:39:49 +09:00
Fix number __format__ (#6930)
This commit is contained in:
1
Lib/test/test_enum.py
vendored
1
Lib/test/test_enum.py
vendored
@@ -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')
|
||||
|
||||
@@ -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))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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))
|
||||
}
|
||||
|
||||
|
||||
@@ -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))
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user