7
votes

I was (maybe wrongfully) thinking that is operator is doing id() comparison.

>>> x = 10
>>> y = 10
>>> id(x)
1815480092
>>> id(y)
1815480092
>>> x is y
True

However, with val is not None, it seems like that it's not that simple.

>>> id(not None)
2001680
>>> id(None)
2053536
>>> val = 10
>>> id(val)
1815480092
>>> val is not None
True

Then, what does 'is' operator do? Is it just object id comparison just I conjectured? If so, val is not None is interpreted in Python as not (val is None)?

3
Yes, val is not None and not (val is None) are equivalent. But the first one is more readable IMO. - Ashwini Chaudhary

3 Answers

10
votes

You missed that is not is an operator too.

Without is, the regular not operator returns a boolean:

>>> not None
True

not None is thus the inverse boolean 'value' of None. In a boolean context None is false:

>>> bool(None)
False

so not None is boolean True.

Both None and True are objects too, and both have a memory address (the value id() returns for the CPython implementation of Python):

>>> id(True)
4440103488
>>> id(not None)
4440103488
>>> id(None)
4440184448

is tests if two references are pointing to the same object; if something is the same object, it'll have the same id() as well. is returns a boolean value, True or False.

is not is the inverse of the is operator. It is the equivalent of not (op1 is op2), in one operator. It should not be read as op1 is (not op2) here:

>>> 1 is not None     # is 1 a different object from None?
True
>>> 1 is (not None)   # is 1 the same object as True?
False
3
votes

As a complement to Martijn Pieters answer, None, True and False are singletons. There is only one instance of each of these values so it is safe to use is to test them..

>>> id(True)
8851952
>>> id(False)
8851920
>>> id(None)
8559264
>>> id(not None)
8851952
>>> id(1 == 0)
8851920
>>> id(1 == 1)
8851952
0
votes

Python tries to emulate the English language syntax to make it more human readable, but in this instance the operator precedence is a little confusing.

>>> val is not None
True

In English, we are asking if val does not have a value that is represented by the same object as None. In your above example val=10, so the answer is (correctly) True.

However, from a logical, syntactical viewpoint you have broken down the statement word-for-word and assumed it to be:

>>> val is (not None)
False

which, when enclosed in appropriate patentheses, returns your expected result (False).

As @Martijn Pieters points out, is not is an operator in its own right, and it the only operator at work here.

If you wanted to write it as a non ambiguous statement using only operators that contain no spaces, you could write:

>>> not (val is None)
True

But that is not how you would 'say' the intended statement in English, or possibly even write it in pseudo-code.