Why Python 3?

Gregory Ewing greg.ewing at canterbury.ac.nz
Sat Apr 19 21:35:57 EDT 2014


Chris Angelico wrote:
> 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?

It doesn't have to be that generic to cause pain. Even if
you're only dealing with floats, the old way meant you had
to stick float() calls all over the place in order to be
sure your divisions do what you want. Not only does that
clutter up and obscure the code, it's needlessy inefficient,
since *most* of the time they don't do anything.

There's also the annoyance that there's more than one
obvious way to do it. Do you write float(x)/y or
x/float(y)? Or do you go for a more symmetrical look
and write float(x)/float(y), even though it's redundant?

The new way makes *all* of that go away. The only downside
is that you need to keep your wits about you and select
the appropriate operator whenever you write a division.
But you had to think about that *anyway* under the old
system, or risk having your divisions silently do the
wrong thing under some circumstances -- and the remedy
for that was very clunky and inefficient.

I'm thoroughly convinced that the *old* way was the
mistake, and changing it was the right thing to do.

> 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.

No, it's not. What the language does is recognise that
there are two kinds of division frequently used, and that
the vast majority of the time you know *when you write the
code* which one you intend. To support this, it provides two
operators. It's still up to the types concerned to implement
those operators in a useful way.

The built-in int and float types cooperate to make // mean
integer division and / mean float division, because that's
the most convenient meanings for them on those types.
Other types are free to do what makes the most sense for
them.

-- 
Greg



More information about the Python-list mailing list