0

I've been working in python for a while now but just now I've encountered an error that I can't explain.

def b():
    return -6
a = b()
if a is -6:
    print("Hi")

Whenever I run this I don't get into the if function and nothing gets printed. but if I make the number bigger than -6 meaning -5, -4 and etc this works properly.

def b():
    return -5
a = b()
if a is -5:
    print("Hi")

can someone explain to me why is this happening? the == operator work as it should but if is it not.

Kshahnazari
  • 135
  • 1
  • 7
  • 2
    related and interesting: https://stackoverflow.com/questions/15171695/whats-with-the-integer-cache-maintained-by-the-interpreter – Tomerikoo Feb 02 '20 at 23:04

1 Answers1

1

== checks if the two values are equal, is checks if the two objects are the same object. So when you create an integer object from your function you need to use ==. Using is here is checking if the function object -6 is the reference to another object -6.

  • 2
    But why `is` recognizes `-5, -4, -3, -1, 0` but not `-6, -7, etc`? Must be a hint for difference in inner representation of these numbers in Python ... – Gwang-Jin Kim Feb 02 '20 at 22:40
  • 4
    @Gwang-JinKim it *shouldn't matter to you*. The interpreter is free to reuse immutable objects if the implementation so desires. You should not have *expected* `is` to work in these cases. That it *happens* to be the case is an implementation detail of CPython, which keeps a small integer cache [-5, 256]. but again, this is an implementation detail, not something you should rely on nor something you should have *expected*. IOW, you should never use *identity* when you mean *equality*. – juanpa.arrivillaga Feb 02 '20 at 22:51
  • With some caution, you can use [`id()` to discover if references point to the same object](https://docs.python.org/3/library/functions.html#id).. further, in cPython, this is actually the memory address of the object. – ti7 Feb 02 '20 at 22:54