Search code examples
pythonnetworkxdeep-copyshallow-copy

Networkx copy clarification


According the doc, it appears that the networkx.copy method does a deep copy of the graph. I'm most concerned about the statement

This makes a complete copy of the graph including all of the node or edge attributes.

Is this suggesting that it makes a copy of what the nodes contain as well? For example if I have the following

class NodeContainer(object):

    def __init__(self, stuff):
        self.stuff = stuff

    # ..other class stuff


g = networkx.DiGraph():

n1 = NodeContainer(stuff1)
n2 = NodeContainer(stuff2)

g.add_edge(n1,n2)

g2 = g.copy()

In the g2 = g.copy() line is it making deep copies of the NodeContainer objects as well? If so, is there an existing implementation of a shallow copy? I have not been able to find one. I ask because I currently have use to create a copy a graph that I will edit (remove nodes from) but not change the actual nodes themselves. So I don't need a deep copy in that sense, just a representation of the graph structure.

EDIT: If possible I'd also like to do a shallow reverse()


Solution

  • You can make a shallow copy by using the class constructor. E.g. for graphs,

    In [1]: import networkx as nx
    
    In [2]: G = nx.Graph()
    
    In [3]: G.add_edge(1,2,l=['a','b','c'])
    
    In [4]: H = nx.Graph(G) # shallow copy
    
    In [5]: H[1][2]['l']
    Out[5]: ['a', 'b', 'c']
    
    In [6]: H[1][2]['l'].append('d')
    
    In [7]: H[1][2]['l']
    Out[7]: ['a', 'b', 'c', 'd']
    
    In [8]: G[1][2]['l']
    Out[8]: ['a', 'b', 'c', 'd']