mirror of
https://github.com/micropython/micropython.git
synced 2026-01-05 11:40:18 +01:00
py/obj: Make mp_obj_get_complex_maybe call mp_obj_get_float_maybe first.
This commit simplifies mp_obj_get_complex_maybe() by first calling mp_obj_get_float_maybe() to handle the cases corresponding to floats. Only if that fails does it attempt to extra a full complex number. This reduces code size and also means that mp_obj_get_complex_maybe() now supports user-defined classes defining __float__; in particular this allows user-defined classes to be used as arguments to cmath-module function. Furthermore, complex_make_new() can now be simplified to directly call mp_obj_get_complex(), instead of mp_obj_get_complex_maybe() followed by mp_obj_get_float(). This also improves error messages from complex with an invalid argument, it now raises "can't convert <type> to complex" rather than "can't convert <type> to float". Signed-off-by: Damien George <damien@micropython.org>
This commit is contained in:
21
tests/float/cmath_dunder.py
Normal file
21
tests/float/cmath_dunder.py
Normal file
@@ -0,0 +1,21 @@
|
||||
# test that cmath functions support user classes with __float__ and __complex__
|
||||
|
||||
try:
|
||||
import cmath
|
||||
except ImportError:
|
||||
print("SKIP")
|
||||
raise SystemExit
|
||||
|
||||
|
||||
class TestFloat:
|
||||
def __float__(self):
|
||||
return 1.0
|
||||
|
||||
|
||||
class TestComplex:
|
||||
def __complex__(self):
|
||||
return 1j + 10
|
||||
|
||||
|
||||
for clas in TestFloat, TestComplex:
|
||||
print("%.5g" % cmath.phase(clas()))
|
||||
@@ -1,6 +1,11 @@
|
||||
# test __complex__ function support
|
||||
|
||||
|
||||
class TestFloat:
|
||||
def __float__(self):
|
||||
return 1.0
|
||||
|
||||
|
||||
class TestComplex:
|
||||
def __complex__(self):
|
||||
return 1j + 10
|
||||
@@ -20,6 +25,7 @@ class Test:
|
||||
pass
|
||||
|
||||
|
||||
print(complex(TestFloat()))
|
||||
print(complex(TestComplex()))
|
||||
|
||||
try:
|
||||
|
||||
15
tests/float/math_dunder.py
Normal file
15
tests/float/math_dunder.py
Normal file
@@ -0,0 +1,15 @@
|
||||
# test that math functions support user classes with __float__
|
||||
|
||||
try:
|
||||
import math
|
||||
except ImportError:
|
||||
print("SKIP")
|
||||
raise SystemExit
|
||||
|
||||
|
||||
class TestFloat:
|
||||
def __float__(self):
|
||||
return 1.0
|
||||
|
||||
|
||||
print("%.5g" % math.exp(TestFloat()))
|
||||
Reference in New Issue
Block a user