Senior Python Quiz: What gets printed and why? ๐ง
Let's test your internal CPython mental model. Take a look at this snippet:
class Key:
def __init__(self, val):
self.val = val
def __hash__(self):
return 1
def __eq__(self, other):
return isinstance(other, Key) and self.val == other.val
d = {}
k1 = Key(1)
d[k1] = "First"
# We mutate the key after insertion
k1.val = 2
# Now we try to retrieve and assign
print(d.get(k1))
d[k1] = "Second"
print(len(d))
What does this code print?
A)
"First"then1B)
Nonethen2C)
"First"then2D)
Nonethen1
I was reviewing a tricky memory state issue with a lead backend engineer on our team, and this exact pattern of key mutation popped up in a production cache layer.
Drop your answer in the comments before running it in your REPL โ and explain the mechanics of lookup vs equality under the hood! ๐
