Merge pull request #355 from NLincoln/compliant-complex-repr

repr() of complex numbers is compliant with cpython
This commit is contained in:
Windel Bouwman
2019-02-06 07:52:31 +01:00
committed by GitHub
2 changed files with 9 additions and 1 deletions

View File

@@ -44,6 +44,9 @@ assert int() == 0
a = complex(2, 4)
assert type(a) is complex
assert type(a + a) is complex
assert repr(a) == '(2+4j)'
a = 10j
assert repr(a) == '10j'
a = 1
assert a.conjugate() == a

View File

@@ -85,5 +85,10 @@ fn complex_conjugate(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult {
fn complex_repr(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult {
arg_check!(vm, args, required = [(obj, Some(vm.ctx.complex_type()))]);
let v = get_value(obj);
Ok(vm.new_str(v.to_string()))
let repr = if v.re == 0. {
format!("{}j", v.im)
} else {
format!("({}+{}j)", v.re, v.im)
};
Ok(vm.new_str(repr))
}