Search code examples
pythonpython-3.xinfinity

Python: 'inf is inf', but '-inf is not -inf'?


Python 3.7

While writing the search code for the maximum, I encountered a strange behavior of negative infinity. Can somebody explain why this behavior?

>>> inf = float('inf')
>>> inf is inf
True
>>> (-inf) is (-inf)
False

And I've already realized it's better to use == for comparison, but I'm interested in the answer to the question above.


Solution

  • inf is a variable, bound to a specific object. Any object is itself, so inf is inf.

    -inf is an expression. It does math, and produces an object with value floating-point negative infinity. Python makes no promises about whether this will be the same object as any other object with that value. In your case, the two evaluations of -inf happened to produce different objects.

    Again, there are no promises about what -inf is -inf will produce. The current CPython implementation happens to consistently produce False. PyPy's primitive handling produces True. A different Python version or implementation might inconsistently produce True or False based on current memory pressure, or whether you ran this as a script or interactively, or any other factor. CPython itself already has cases where object identity is different in a script or interactively; for example, this:

    x = 1000
    y = 1000
    print(x is y)
    

    prints different things in the current CPython implementation depending on whether you run it interactively.