2

I'm used to pointers and references, but I need some clarification on this point:

I have this method in my Node class:

def createNewNode(graph):
    #Create New Node Dictionary
    newNode = {}
    # Fill in Details for that Node
    newNode['NAME'] = 'Max'
    newNode['AGE'] = 22
    newNode['ID'] = 'DC1234SH987'
    #Add the Node to the Graph
    graph.addNode(newNode)

The scope of the newNode created is within the function createNewNode(). Now this Node is added to a list of nodes in the Graph class.

The Graph class has this function:

def addNode(self, node):
    self.nodeList.append(node)

Now the Graph class function addNode() just appends the node to the list of nodes in the graph class. After the call to graph.addNode() in the node class, when does the scope of the newNode variable stop existing?

Won’t the data that was appended to the list in the Graph class be invalid now? Does append() makes a new copy of the object passed? Can you explain this to me?

(In this example, the graph just contains a list of nodes and the node is actually a dictionary with details.)

alexwlchan
  • 5,699
  • 7
  • 38
  • 49
  • [9.1 and 9.2 of the Tutorial](https://docs.python.org/2.7/tutorial/classes.html#a-word-about-names-and-objects) is a good read, As well as [3.1](https://docs.python.org/2.7/reference/datamodel.html#data-model) and [4.1](https://docs.python.org/2.7/reference/datamodel.html#data-model) of the Language Reference in the docs. – wwii Mar 17 '15 at 18:51

1 Answers1

5

The name newNode goes out of scope, but the object it refers to is not destroyed. You added another reference to that object by appending it to nodeList. append doesn't make a copy, but it does create a separate reference to the same object. A name goes out of scope when the function it is in ends, but an object is only garbage collected when all references to it are gone.

BrenBarn
  • 242,874
  • 37
  • 412
  • 384
  • @VishrutReddi - this could be *visualized* by printing the [```id```](https://docs.python.org/2.7/library/functions.html#id), of the new node, inside the two methods and after the ```addNode``` method has *finished*. – wwii Mar 17 '15 at 18:36