From 2aa58cc551962331a813a06bb985d723b5c6f9ea Mon Sep 17 00:00:00 2001 From: Snowapril Date: Sun, 29 Aug 2021 11:33:56 +0900 Subject: [PATCH] implement `complex.__complex__` add `complex.__complex__` which will be added in cpython 3.11 for typing module. documents: * https://docs.python.org/3.11/whatsnew/3.11.html#other-cpython-implementation-changes * https://bugs.python.org/issue24234 Signed-off-by: snowapril --- extra_tests/snippets/complex.py | 15 +++++++++++++++ vm/src/builtins/complex.rs | 9 +++++++++ 2 files changed, 24 insertions(+) create mode 100644 extra_tests/snippets/complex.py 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