meke meke meke meke - 22 days ago 4
Python Question

Why is data contamination?

# -*- coding: utf-8 -*-

import random, pprint
user = {}
USERINFO_STRUCT = {
'id': '',
}

def client_new(id):
global user

newuser = USERINFO_STRUCT
newuser['id'] = id
user[id] = newuser

pprint.pprint(user)
print ""

client_new(1)
client_new(2)
client_new(3)


I want results:

{1: {'id': 1}}

{1: {'id': 1}, 2: {'id': 2}}

{1: {'id': 1}, 2: {'id': 2}, 3: {'id': 3}}


The results of that code execution is:

{1: {'id': 1}}

{1: {'id': 2}, 2: {'id': 2}}

{1: {'id': 3}, 2: {'id': 3}, 3: {'id': 3}}


How are you doing this?

My machine is Debian Linux 8.6 (Python 2.7.9).

AJK AJK
Answer

In python, dictionaries and lists are copied by reference:

>>> a = [0]
>>> b = a
>>> b
[0]
>>> a
[0]
>>> b[0] = 2
>>> a
[2]
>>> b
[2]

So, b and a refer to the same list in the python memory and modifying one modifies the other.

So, what you can do is when you want to create another copy of a list or dictionary, make a copy. For a list:

>>> b = a[:]  # for a list

For a dictionary:

>>> b = a.copy()  # for a dictionary

So, in your code, what you need is to copy the USERINFO_STRUCT into the newuser using newuser = USERINFO_STRUCT.copy()

Comments