Python 3 and PEP238 division

Ninereeds stephenhorne100 at aol.com
Mon Mar 17 15:13:45 CET 2008

```Is the PEP238 change to division going into Python 3 as planned?

I realise that the new integer division semantics have been available
in "from __future__" for quite a few years now, but a warning might be
appropriate now that Python 3 is in alpha. A lot of people have
probably either forgotten, or else never knew about PEP238. The
following wording is still included in the Python 2.5.1
documentation...

"""
3.1.1 Numbers
The interpreter acts as a simple calculator: you can type an
expression at it and it will write the value. Expression syntax is
straightforward: the operators +, -, * and / work just like in most
other languages (for example, Pascal or C); parentheses can be used
for grouping. For example:

>>> 2+2
4
>>> # This is a comment
... 2+2
4
>>> 2+2  # and a comment on the same line as code
4
>>> (50-5*6)/4
5
>>> # Integer division returns the floor:
... 7/3
2
>>> 7/-3
-3
"""

Which is interesting, since neither Pascal nor C division works like
that. Pascal has a separate 'div' operator for integer division. C and
C++ compilers usually round toward zero IIRC, but the rounding
direction is not defined in the standards. In any case, after the
final adoption of PEP238, integer division in Python will generally
return float results - not the rounded-to-floor integer results shown
here.

It might be worth brainstorming some contexts where problems are
likely to occur, to help anyone trying to prepare for the change.

My contribution to that would be any code that needs to partition
lists into slices. The obvious cases - binary searching, sorting - are
covered by libraries which should be used in preference to hand-
written code, but this kind of thing can happen elsewhere. I have some
code that organises a sorted list of data into a balanced tree as part
of a code generation task, for example, which relies on floor
division.

Also, if money amounts are stored as integer numbers of pennies (which
they often are, since floats represent approximate values) problems
could occur with various calculations since multiplication by a
fractional quantity is often represented as a multiplication followed
by a division. For example adding 5% is equivalent to multiplying by
1.05, or to multiplying by 105 then dividing by 100. The latter idiom
is often used to keep everything integer, which requires division
results to be rounded.

Use of the decimal module is probably a good idea for money amounts
these days, of course. I've not used it myself but the whole point of
a decimal number type would be to get exact results and the kind of
rounding behaviour that accountants would expect.

The real world fix would normally be to replace the / operator
with //, though, in order to keep the old floor-division semantics.

```

More information about the Python-list mailing list