The math module provides mathematical functions that operate on floating-point values. However, several of its functions accept only integers and return results that are exact rather than approximate. Keeping both kinds in a single namespace made the distinction harder to see, since nothing in a function name indicated which domain it belonged to.
Since Python 3.15, the standard library provides the math.integer module, which gathers the integer-specific functions in one place. It contains the following functions:
comb- returns the number of ways to choose items without repetition and without order.factorial- returns the factorial of a nonnegative integer.gcd- returns the greatest common divisor of its arguments.isqrt- returns the integer square root of a nonnegative integer.lcm- returns the least common multiple of its arguments.perm- returns the number of ways to choose items without repetition and with order.
These functions accept integers and any object implementing the __index__ method, which is used to convert the object to an integer number. All return values are computed exactly and are integers, so none of them produces a floating-point result.
The functions have been part of the math module for several releases and can still be called from there:
import math
print(math.gcd(12, 18)) # 6
print(math.lcm(4, 6)) # 12
print(math.isqrt(17)) # 4
print(math.comb(5, 2)) # 10
print(math.perm(5, 2)) # 20
print(math.factorial(5)) # 120
Since Python 3.15, the same calls can be written using the math.integer module:
from math import integer
print(integer.gcd(12, 18)) # 6
print(integer.lcm(4, 6)) # 12
print(integer.isqrt(17)) # 4
print(integer.comb(5, 2)) # 10
print(integer.perm(5, 2)) # 20
print(integer.factorial(5)) # 120
The API remains unchanged, only the import path is different. Each function accepts the same arguments and produces the same values, so moving existing code to the math.integer module requires no other edits.
Leave a Comment
Cancel reply