4

I was given a Python test and one of the questions was: what should be passed to the following function, so that it will return True?

def fun(x):
    if x + 1 is 1 + x:
        return False
    if x + 2 is not 2 + x:
        return False
    return True

In my opinion this doesn't make much sense but I just would like to know the right answer (if such answer exists).

NoDataDumpNoContribution
  • 10,591
  • 9
  • 64
  • 104
nmospan
  • 139
  • 4
  • 2
    Without cooking up my own class which implements addition in a weird way, I don't see how this could work. You've got me curious. – Daniel Walker Aug 29 '20 at 16:51
  • 4
    Cpython cache integers, which means that some share identity. When you have numbers that are bigger than this range, they'll be newly created and thus have different id's. Don't remember the exact range though – Ted Klein Bergman Aug 29 '20 at 16:54
  • 1
    If you're interested in more weird behaviour like this, check out [pywat](https://github.com/cosmologicon/pywat) – wjandrea Aug 29 '20 at 16:54
  • 1
    Since cpython caches -5 to 256 I can be lazy and have python figure it out: `[i for i in range(-10, 300) if fun(i)]` – tdelaney Aug 29 '20 at 16:57
  • See also [What's with the integer cache maintained by the interpreter?](https://stackoverflow.com/questions/15171695/whats-with-the-integer-cache-maintained-by-the-interpreter) – NoDataDumpNoContribution Aug 29 '20 at 17:05

1 Answers1

11

This has to do with how python caches small numbers: https://stackoverflow.com/a/48120163/13003236

Typically, is is used to check if two variables are the same object instead of if they have the same value. However, because of how python caches small numbers, calling is on numbers from -5 to 256 has the same effect as comparing them. So, this function returns true if x + 1 is less than -5, but x + 2 is greater than or equal to -5. That means that passing -7 into this function will cause it to succeed.

Simon Shkolnik
  • 368
  • 3
  • 12