diff --git a/extra_tests/snippets/complex.py b/extra_tests/snippets/complex.py new file mode 100644 index 0000000000..6858a1521b --- /dev/null +++ b/extra_tests/snippets/complex.py @@ -0,0 +1,15 @@ +import testutils + +# __complex__ +def test__complex__(): + z = 3 + 4j + assert z.__complex__() == z + assert type(z.__complex__()) == complex + + class complex_subclass(complex): + pass + z = complex_subclass(3 + 4j) + assert z.__complex__() == 3 + 4j + assert type(z.__complex__()) == complex + +testutils.skip_if_unsupported(3,11,test__complex__) \ No newline at end of file diff --git a/vm/src/builtins/complex.rs b/vm/src/builtins/complex.rs index 1c2f0145e0..52374d9657 100644 --- a/vm/src/builtins/complex.rs +++ b/vm/src/builtins/complex.rs @@ -89,6 +89,15 @@ impl PyComplex { self.value } + #[pymethod(magic)] + fn complex(zelf: PyRef, vm: &VirtualMachine) -> PyRef { + if zelf.is(&vm.ctx.types.complex_type) { + zelf + } else { + PyComplex::from(zelf.value).into_ref(vm) + } + } + #[pyproperty] fn real(&self) -> f64 { self.value.re