Skip to content

Commit f8373aa

Browse files
author
Nicolas Trinquier
committed
Add mul method for the complex type
1 parent e3e2e7f commit f8373aa

File tree

2 files changed

+17
-0
lines changed

2 files changed

+17
-0
lines changed

tests/snippets/builtin_complex.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,11 @@
2424
assert complex(1, 2) != 'foo'
2525
assert complex(1, 2).__eq__('foo') == NotImplemented
2626

27+
# __mul__
28+
29+
assert complex(2, -3) * complex(-5, 7) == complex(-21, 29)
30+
assert complex(2, -3) * 5 == complex(10, -15)
31+
2732
# __neg__
2833

2934
assert -complex(1, -1) == complex(-1, 1)

vm/src/obj/objcomplex.rs

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -161,6 +161,18 @@ impl PyComplex {
161161
vm.ctx.new_bool(result)
162162
}
163163

164+
#[pymethod(name = "__mul__")]
165+
fn mul(self, other: PyObjectRef, vm: &VirtualMachine) -> PyObjectRef {
166+
match to_complex(other, vm) {
167+
Ok(Some(other)) => Ok(vm.ctx.new_complex(Complex64::new(
168+
self.value.re * other.re - self.value.im * other.im,
169+
self.value.re * other.im + self.value.re * other.im,
170+
))),
171+
Ok(None) => Ok(vm.ctx.not_implemented()),
172+
Err(err) => Err(err),
173+
}
174+
}
175+
164176
#[pymethod(name = "__neg__")]
165177
fn neg(&self, _vm: &VirtualMachine) -> PyComplex {
166178
PyComplex::from(-self.value)

0 commit comments

Comments
 (0)