CodeQL documentation

Result of integer division may be truncated

ID: py/truncated-division
Kind: problem
Security severity: 
Severity: warning
Precision: very-high
Tags:
   - maintainability
   - correctness
Query 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, add from __future__ import division 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:

def average(l):
    return sum(l) / len(l)

print average([1.0, 2.0])  # Prints "1.5".
print average([1, 2])      # Prints "1", which is incorrect.
# Correct:
from __future__ import division

def average(l):
    return sum(l) / len(l)

print average([1.0, 2.0])  # Prints "1.5".
print average([1, 2])      # Prints "1.5".

References

  • © GitHub, Inc.
  • Terms
  • Privacy