Why does Python 3.x have unusual floored (integer) division behaviour?

263 views Asked by At

Since the Python integer division operator (a // b) always returns a value which can be safely stored in an int without losing precision (no matter of values for a and b), why is the following true?

If one or both operands are of type float, this operator returns a float.

Only if both operands are of type int will this operator return an int.

Wouldn't it be more consistent if every implementation of __floordiv__ returned an int?

1

There are 1 answers

1
Martijn Pieters On BEST ANSWER

Python states that both arguments are coerced to a common type. From the Numeric types documentation:

Python fully supports mixed arithmetic: when a binary arithmetic operator has operands of different numeric types, the operand with the “narrower” type is widened to that of the other, where integer is narrower than floating point, which is narrower than complex.

And from the Arithmetic conversions section of the Expressions documentation:

When a description of an arithmetic operator below uses the phrase “the numeric arguments are converted to a common type,” this means that the operator implementation for built-in types works as follows:

  • If either argument is a complex number, the other is converted to complex;
  • otherwise, if either argument is a floating point number, the other is converted to floating point;
  • otherwise, both must be integers and no conversion is necessary.

and the Binary arithmetic operations section (which includes floor division) then uses that phrasing:

The / (division) and // (floor division) operators yield the quotient of their arguments. The numeric arguments are first converted to a common type.

The floor division operator is no exception; the behaviour is exactly the same across all arithmetic operators.

If floor division were to behave differently, it would be the exception to this rule, creating inconsistent behaviour, rather than being more consistent.