Result of integer division may be truncated¶
ID: py/truncated-divisionKind: problemSecurity severity: Severity: warningPrecision: very-highTags: - maintainability - correctnessQuery suites: - python-security-and-quality.qls
Click to see the query in the CodeQL repository
In Python 2, the result of dividing two integers is silently truncated into an integer. This may lead to unexpected behavior.
Recommendation¶
If the division should never be truncated, addfrom__future__importdivision to the beginning of the file. If the division should always be truncated, replace the division operator/ with the truncated division operator//.
Example¶
The first example shows a function for calculating the average of a sequence of numbers. When the function runs under Python 2, and the sequence contains only integers, an incorrect result may be returned because the result is truncated. The second example corrects this error by following the recommendation listed above.
# Incorrect:defaverage(l):returnsum(l)/len(l)printaverage([1.0,2.0])# Prints "1.5".printaverage([1,2])# Prints "1", which is incorrect.
# Correct:from__future__importdivisiondefaverage(l):returnsum(l)/len(l)printaverage([1.0,2.0])# Prints "1.5".printaverage([1,2])# Prints "1.5".
References¶
Python Language Reference:Binary arithmetic operations.
PEP 238:Changing the Division Operator.
PEP 236:Back to thefuture.