this post was submitted on 26 Feb 2025
24 points (100.0% liked)

Python

6723 readers
1 users here now

Welcome to the Python community on the programming.dev Lemmy instance!

πŸ“… Events

PastNovember 2023

October 2023

July 2023

August 2023

September 2023

🐍 Python project:
πŸ’“ Python Community:
✨ Python Ecosystem:
🌌 Fediverse
Communities
Projects
Feeds

founded 2 years ago
MODERATORS
 
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()

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

you are viewing a single comment's thread
view the rest of the comments
[–] technohacker 10 points 5 days ago* (last edited 5 days ago) (1 children)

Oh I had a similar bug but with defaulted dicts. Default args are constructed once and reused. Not a problem for immutable args, but mutables like dicts (and sets I'd also assume) are all shared.

EDIT: whoops, didn't see you spoilered the answer, my bad! If it helps, i found my bug when dealing with cross-thread stuff, so that was a fun moment to bisect

[–] [email protected] 4 points 5 days ago (1 children)

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"]
[–] technohacker 1 points 5 days ago

Ah sorry I meant a default argument which was a dict, thanks for the tip tho!