Skip to content

Commit 12e6de0

Browse files
author
Nathan
committed
repr() of complex numbers is compliant with cpython
1 parent aaf0eab commit 12e6de0

File tree

2 files changed

+9
-1
lines changed

2 files changed

+9
-1
lines changed

tests/snippets/basic_types.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,9 @@
4444
a = complex(2, 4)
4545
assert type(a) is complex
4646
assert type(a + a) is complex
47+
assert repr(a) == '(2+4j)'
48+
a = 10j
49+
assert repr(a) == '10j'
4750

4851
a = 1
4952
assert a.conjugate() == a

vm/src/obj/objcomplex.rs

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -85,5 +85,10 @@ fn complex_conjugate(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult {
8585
fn complex_repr(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult {
8686
arg_check!(vm, args, required = [(obj, Some(vm.ctx.complex_type()))]);
8787
let v = get_value(obj);
88-
Ok(vm.new_str(v.to_string()))
88+
let repr = if v.re == 0. {
89+
format!("{}j", v.im)
90+
} else {
91+
format!("({}+{}j)", v.re, v.im)
92+
};
93+
Ok(vm.new_str(repr))
8994
}

0 commit comments

Comments
 (0)