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
?
Python states that both arguments are coerced to a common type. From the Numeric types documentation:
And from the Arithmetic conversions section of the Expressions documentation:
and the Binary arithmetic operations section (which includes floor division) then uses that phrasing:
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.