0

I'm trying to create classes for a network, but data is getting shared between nodes. I do not want data to be shared between nodes. I am not sure why this is happening. I have this code so far:

class Node:
    def __init__(self, data=dict()):
        self.data = data

class Network:
    def __init__(self):
        self.nodes = dict()
        
    def add_node(self, node_id, data=dict()):
        self.nodes[node_id] = Node(data=data)

Depending on how I add a node to the network, there seems to be an issue of data being shared between nodes. I demonstrate this below:

Firstly, if I add nodes without data, then insert data to the nodes, the data gets shared between the nodes.

nx = Network()
nx.add_node('a')
nx.add_node('b')
nx.nodes['a'].data['numbers'] = 123
nx.nodes['a'].data, nx.nodes['b'].data

Outputs:

({'numbers': 123}, {'numbers': 123})

So without adding data to the 'b' node, somehow its data gets populated with the data added to the 'a' node.

Now, if I avoid the add_node method, like this, I get a different outcome:

nx.nodes['c'] = Node(data = {'foo': 291284})
nx.nodes['c'].data

I get this output:

{'foo': 291284}

And nodes 'a' and 'b' remain as they were:

nx.nodes['a'].data, nx.nodes['b'].data

Outputs:

({'numbers': 123}, {'numbers': 123}

Where am I going wrong here? If I add data to node 'a', I only want node 'a' to have that data, it should not get shared.

Data
  • 689
  • 7
  • 23
  • In both classes there is mutable default argument in one of the methods - `data` default value is `dict` (i.e. mutable object). – buran May 18 '22 at 17:54
  • Thank you. And I suppose this gives the solution for how to do this correctly: https://stackoverflow.com/questions/366422/what-is-the-pythonic-way-to-avoid-default-parameters-that-are-empty-lists – Data May 18 '22 at 17:58
  • The [link we shared](https://stackoverflow.com/q/1132941/4046632) when closed the question as dupe also show how to do it. Your link would do as well. – buran May 18 '22 at 18:00

0 Answers0