Beware of the identity operator 'is'.

The code in Finder._order() of find.py is aromatic. One line, line 209, goes beyond being merely aromatic. It scares me. The following shows my fears for using the 'is' operator. For each of the following cells, predict the output before looking at the output.

Imagine an implementation of Python that would have multiple True objects.


In [1]:
1 == True


Out[1]:
True

In [2]:
1 is True


Out[2]:
False

In [3]:
a = 10**6
b = a  # b refers to same object as a.
print(a, b, a == b, a is b)

b += 1
print(a, b, a == b, a is b)

b -= 1  # b has same value as a, but refers to different object than a.
print(a, b, a == b, a is b)


1000000 1000000 True True
1000000 1000001 False False
1000000 1000000 True False

In [4]:
# This implementation of Python shares objects for small numbers.
# I think this behavior is _not_ guaranteed.

a = 5
b = 5
print(a, b, a == b, a is b)

b += 1
print(a, b, a == b, a is b)

b -= 1
print(a, b, a == b, a is b)


5 5 True True
5 6 False False
5 5 True True

In [5]:
# 1 and True have the same value, but are different objects.
# I think that this implementation Python shares objects for True.
# I think that this behavior is not guaranteed.

a = 1
b = 1
print(a, b, a == b, a is b)

a = True
print(a, b, a == b, a is b)

b = True
print(a, b, a == b, a is b)

b += 1
print(a, b, a == b, a is b)

b -= 1
print(a, b, a == b, a is b)

b = (a == b)
print(a, b, a == b, a is b)


1 1 True True
True 1 True False
True True True True
True 2 False False
True 1 True False
True True True True