[Python-3000] Math in Python 3.0

Giovanni Bajo rasky at develer.com
Sun May 14 13:20:32 CEST 2006


Nick Coghlan <ncoghlan at gmail.com> wrote:

>> For example, square roots are known as math.sqrt(x) for floats,
>> cmath.sqrt(x) for complex numbers, x.sqrt() for decimals, and
>> gmpy.sqrt(x)/gmpy.fsqrt(x) for gmpy's types. Oh, and SciPy has its
>> own sqrt function that works on arrays (but not Decimals or gmpy's
>> types).
>
> Py3k's function overloading should fix this:
>
> @overloaded
> def sqrt(value):
>      raise TypeError("Cannot take square root of %s" %
> type(value).__name__)
>
> @sqrt.overload
> def sqrt_float(value : float):
>      return math.sqrt(value)
>
> @sqrt.overload
> def sqrt_complex(value : complex):
>      return cmath.sqrt(value)
>
> @sqrt.overload
> def sqrt_decimal(value : decimal):
>      return value.sqrt()
>
> # Similar overloads can be added for the types in gmpy and numpy.


So, are we totally dropping the "special-cased __ method" that worked so fine
till now? I can "overload" abs() for my point type (to return its modulus) just
by defining a __abs__, and it works fine. In such a world (called Python 2.x),
I wouldn't find so strange if I had a __sqrt__.

It's just a different way of dispatching, in the end. But I think that we
should use a consistent way for, eg., all the math functions.

Giovanni Bajo



More information about the Python-3000 mailing list