Reputation: 3891
I am quite surprised at the behavior of this code, which is inside a function:
for user in full_details["users"]:
user = collections.defaultdict(lambda: False, user)
if user["comments"]:
user["comments"] = [comment.__dict__ for comment in user["comments"]]
print("just converted user comments to dict objects")
print(user["comments"])
print("printing full details")
print(full_details)
My understanding was that if I modified a dictionary or a list, that modification applied to the object and would remain. However, when I change user["comments"]
for each user in full_details["users"]
within my if
I am not then seeing those same changes again reflected in full_details
just immediately after. Why is that? I thought that whenever you create a new list and assign it to a passed-in parameter, that new list will persist outside the function.
My trouble is that the change made here does not persist:
user["comments"] = [comment.__dict__ for comment in user["comments"]]
Also, full_details is a default_dict:
full_details = collections.defaultdict(lambda: False, thread_details.__dict__)
Upvotes: 0
Views: 86
Reputation: 1929
You are assigning "user" twice. First in the for statement. Then in the first line of the body of the for loop, you are creating a new object and also assigning it to "user". At this point, you have lost your reference to the original object.
Upvotes: 1