Skip to main content

Command Palette

Search for a command to run...

Senior Python Quiz: What gets printed and why? ๐Ÿง 

Updated
โ€ข1 min readโ€ขView as Markdown

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" then 1

  • B) None then 2

  • C) "First" then 2

  • D) None then 1

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! ๐Ÿ‘‡