PEP: 238 Title: Non-integer Division Version: $Revision$ Author: pep@zadka.site.co.il (Moshe Zadka) Status: Draft Type: Standards Track Created: 11-Mar-2001 Python-Version: 2.2 Post-History: 16-Mar-2001 Abstract Dividing integers currently returns the floor of the quantities. This behavior is known as integer division, and is similar to what C and FORTRAN do. This has the useful property that all operations on integers return integers, but it does tend to put a hump in the learning curve when new programmers are surprised that 1/2 == 0 This proposal shows a way to change this while keeping backward compatibility issues in mind. Rationale The behavior of integer division is a major stumbling block found in user testing of Python. This manages to trip up new programmers regularly and even causes the experienced programmer to make the occasional mistake. The workarounds, like explicitly coercing one of the operands to float or use a non-integer literal, are very non-intuitive and lower the readability of the program. // Operator A `//' operator which will be introduced, which will call the nb_intdivide or __intdiv__ slots. This operator will be implemented in all the Python numeric types, and will have the semantics of a // b == floor(a/b) Except that the type of a//b will be the type a and b will be coerced into. Specifically, if a and b are of the same type, a//b will be of that type too. Changing the Semantics of the / Operator The nb_divide slot on integers (and long integers, if these are a separate type, but see PEP 237 [1]) will issue a warning when given integers a and b such that a % b != 0 The warning will be off by default in the 2.2 release, and on by default for in the next Python release, and will stay in effect for 24 months. The next Python release after 24 months, it will implement (a/b) * b = a (more or less) The type of a/b will be either a float or a rational, depending on other PEPs[2, 3]. __future__ A special opcode, FUTURE_DIV will be added that does the equivalent of: if type(a) in (types.IntType, types.LongType): if type(b) in (types.IntType, types.LongType): if a % b != 0: return float(a)/b return a/b (or rational(a)/b, depending on whether 0.5 is rational or float). If "from __future__ import non_integer_division" is present in the module, until the IntType nb_divide is changed, the "/" operator is compiled to FUTURE_DIV. Open Issues Should the // operator be renamed to "div"? Should the // be made into a function called "div"? References [1] PEP 237, Unifying Long Integers and Integers, Zadka, http://www.python.org/peps/pep-0237.html [2] PEP 239, Adding a Rational Type to Python, Zadka, http://www.python.org/peps/pep-0239.html [3] PEP 240, Adding a Rational Literal to Python, Zadka, http://www.python.org/peps/pep-0240.html Copyright This document has been placed in the public domain. Local Variables: mode: indented-text indent-tabs-mode: nil End: