on-internet
← Community

Why does my dict get shared between function calls?

Stack Overflow ·

I have this little cache thing and it behaves weird. The second time I call the function the list inside already has stuff from the first call. I thought maybe it's a global or something but I don't have any global. def get_items(key, cache={}): if key not in cache: cache[key] = [] cache[key].append(len(cache[key]) + 1) return cache[key] print(get_items("a")) # [1] print(get_items("b")) # [1] <-- why?? print(get_items("a")) # [1, 2] I expected get_items("b") to give [1] fresh but it looks like the default {} is being reused across calls. Is that really a thing in Python or am I doing something

Comments

Sign in or sign up to comment and upvote.

No comments yet.