Skip to content

Commit 177704f

Browse files
Merge pull request RustPython#891 from ntrinquier/add-methods-for-numeric-types
Add methods for the complex type
2 parents 132d34f + 490db0a commit 177704f

File tree

2 files changed

+30
-1
lines changed

2 files changed

+30
-1
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(11, 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: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -67,7 +67,9 @@ impl PyComplexRef {
6767
}
6868

6969
fn to_complex(value: PyObjectRef, vm: &VirtualMachine) -> PyResult<Option<Complex64>> {
70-
if objtype::isinstance(&value, &vm.ctx.int_type()) {
70+
if objtype::isinstance(&value, &vm.ctx.complex_type()) {
71+
Ok(Some(get_value(&value)))
72+
} else if objtype::isinstance(&value, &vm.ctx.int_type()) {
7173
match objint::get_value(&value).to_f64() {
7274
Some(v) => Ok(Some(Complex64::new(v, 0.0))),
7375
None => Err(vm.new_overflow_error("int too large to convert to float".to_string())),
@@ -161,6 +163,28 @@ impl PyComplex {
161163
vm.ctx.new_bool(result)
162164
}
163165

166+
#[pymethod(name = "__float__")]
167+
fn float(&self, vm: &VirtualMachine) -> PyResult {
168+
return Err(vm.new_type_error(String::from("Can't convert complex to float")));
169+
}
170+
171+
#[pymethod(name = "__int__")]
172+
fn int(&self, vm: &VirtualMachine) -> PyResult {
173+
return Err(vm.new_type_error(String::from("Can't convert complex to int")));
174+
}
175+
176+
#[pymethod(name = "__mul__")]
177+
fn mul(&self, other: PyObjectRef, vm: &VirtualMachine) -> PyResult {
178+
match to_complex(other, vm) {
179+
Ok(Some(other)) => Ok(vm.ctx.new_complex(Complex64::new(
180+
self.value.re * other.re - self.value.im * other.im,
181+
self.value.re * other.im + self.value.im * other.re,
182+
))),
183+
Ok(None) => Ok(vm.ctx.not_implemented()),
184+
Err(err) => Err(err),
185+
}
186+
}
187+
164188
#[pymethod(name = "__neg__")]
165189
fn neg(&self, _vm: &VirtualMachine) -> PyComplex {
166190
PyComplex::from(-self.value)

0 commit comments

Comments
 (0)