I am working on a music player which has a strict Source Lines of Code (SLoC) count. When looking for ways to lower that count, I discovered that I was importing the math module, just to floor a variable. In an attempt to remove the import statement, I looked at the official documentation for math.floor, and I saw this:
...If x is not a float, delegates to x.__floor__, which should return an Integral value.
When I went to the x.__floor__ link, I found this:
object.__round__(self[, ndigits])
object.__trunc__(self)
object.__floor__(self)
object.__ceil__(self)
Called to implement the built-in function round() and math functions trunc(), floor() and ceil()....
Basically, instead of running the following:
import math float_value = 4.72 print(math.trunc(float_value)) # 4 print(math.floor(float_value)) # 4 print(math.ceil(float_value)) # 5
you can instead run the following:
float_value = 4.72 print(float_value.__trunc__()) # 4 print(float_value.__floor__()) # 4 print(float_value.__ceil__()) # 5
getting rid of the math dependency, and importantly in this case, one line.