You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
The functions in the math module have the (pleasantly) surprising and
apparently undocumented property that they'll accept not just floats, but any Python object having a float method:
>>> classtest1(object):
... def__float__(self):
... return3.
...
>>> from math import sqrt
>>> sqrt(test1())
1.7320508075688772
Based on this, one might expect the functions in the complex math module cmath to have the same property with respect to __complex__.
But this isn't so:
>>> classtest2(object):
... def__complex__(self):
... return-3+0j
...
>>> from cmath import sqrt as csqrt
>>> csqrt(test2())
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: a float is required
The real surprise is that the cmath functions *will* call the __float__ method, if it's available:
>>> csqrt(test1())
(1.7320508075688772+0j)
This patch expands the PyComplex_AsCComplex method so that it looks for a __complex__ method before looking for the __float__ method. This `fixes' the above behaviour.
Should it be a documented feature that the math functions will make use of __float__? If so, and if the patched behaviour seems desirable, I'll add suitable tests to test_math and test_cmath.
Activity
mdickinson commentedon Mar 7, 2007
The functions in the math module have the (pleasantly) surprising and
apparently undocumented property that they'll accept not just floats, but any Python object having a float method:
Based on this, one might expect the functions in the complex math module cmath to have the same property with respect to __complex__.
But this isn't so:
The real surprise is that the cmath functions *will* call the __float__ method, if it's available:
This patch expands the PyComplex_AsCComplex method so that it looks for a __complex__ method before looking for the __float__ method. This `fixes' the above behaviour.
Should it be a documented feature that the math functions will make use of __float__? If so, and if the patched behaviour seems desirable, I'll add suitable tests to test_math and test_cmath.
birkenfeld commentedon Mar 12, 2007
I think it is the right thing to do.
Test cases would be welcome.
birkenfeld commentedon Mar 12, 2007
Please include both old-style and new-style classes in the test case, and for each one test if the check for a complex return from __complex__ works.
mdickinson commentedon Mar 17, 2007
File Added: complex_patch.patch
birkenfeld commentedon Mar 17, 2007
OK, thank you! Committed the patch, new tests and docs in rev. 54421.