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.

  • unalivejoy@lemm.ee
    link
    fedilink
    English
    arrow-up
    3
    ·
    13 hours ago

    You may like collections.defaultdict. Pass the constructor a factory function to be run when a key is missing.

    dd = defaultdict(list)
    dd['key'].append("value")
    print(dd['key'])  # ["value"]