Why Python 3?

Chris Angelico rosuav at gmail.com
Sat Apr 19 16:53:00 EDT 2014


On Sun, Apr 20, 2014 at 6:38 AM, Ian Kelly <ian.g.kelly at gmail.com> wrote:
>> Or you just cast one of them to float. That way you're sure you're
>> working with floats.
>
> Which is inappropriate if the type passed in was a Decimal or a complex.

In that case, you already have a special case in your code, so whether
that special case is handled by the language or by your code makes
little difference. Is your function so generic that it has to be able
to handle float, Decimal, or complex, and not care about the
difference, and yet has to ensure that int divided by int doesn't
yield int? Then say so; put in that special check. Personally, I've
yet to meet any non-toy example of a function that needs that exact
handling; most code doesn't ever think about complex numbers, and a
lot of things look for one specific type:

>>> "asdf"*3.0
Traceback (most recent call last):
  File "<pyshell#19>", line 1, in <module>
    "asdf"*3.0
TypeError: can't multiply sequence by non-int of type 'float'

Maybe it's not your code that should be caring about what happens when
you divide two integers, but the calling code. If you're asking for
the average of a list of numbers, and they're all integers, and the
avg() function truncates to integer, then the solution is to use sum()
and explicitly cast to floating point before dividing. Why should the
language handle that? It's no different from trying to sum a bunch of
different numeric types:

>>> sum([1.0,decimal.Decimal("1")])
Traceback (most recent call last):
  File "<pyshell#25>", line 1, in <module>
    sum([1.0,decimal.Decimal("1")])
TypeError: unsupported operand type(s) for +: 'float' and 'decimal.Decimal'

The language doesn't specify a means of resolving the conflict between
float and Decimal, but for some reason the division of two integers is
blessed with a language feature. Again, it would make perfect sense if
float were a perfect superset of int, so that you could simply declare
that 1.0 and 1 behave absolutely identically in all arithmetic (they
already hash and compare equally), but that's not the case, so I don't
see that division should try to pretend they are.

ChrisA



More information about the Python-list mailing list