class Node:
    def __init__(self, edges = set()):
        self.edges = edges


def main():
    foo = Node()
    bar = Node()
    quz = Node()

    foo.edges.add(bar)
    bar.edges.add(foo)

    assert(foo is not bar) # assertion succeeds
    assert(foo is not quz) # assertion succeeds
    assert(bar is not quz) # assertion succeeds
    assert(len(quz.edges) == 0) # assertion fails??


main()
spoiler

Mutable default values are shared across objects. The set in this case.

  • @waz
    link
    1
    edit-2
    5 days ago

    Wow, I learned this bug during a job interview I had this week. I’m not much of a Python guy, but I was givin a Python coding challenge and I tried default initializing a parameter to an empty list. The guy interviewing me looked horrified and explained the problem and sent me an article about it to read later. It’s a odd coincidence coming across it twice in one week.