Vikas Prasad
Vikas Prasad

Reputation: 3433

An object is being treated as NoneType in Python 2.7.6

There is a class Tree234 which has just one member _pRoot, which is a Node type object. The Node here itself is a class.

Now, when I am trying to use _pRoot directly in any method of the Tree234 class, it is working. But when I try to use it via a temporary variable equating it to _pRoot, it isn't working.

Below is the relevant piece of code:

class Tree234:
    #_pRoot = None

    def __init__(self):
        self._pRoot = Node()

    def find(self, key):
        pass

    def insert(self, dValue):
        pCurNode = self._pRoot
        pTempItem = DataItem(dValue)

        while True:
            if pCurNode.isFull():
                self.split(pCurNode)
                pCurNode = pCurNode.getParent()
                pCurNode = self.getNextChild(pCurNode, dValue)

            elif pCurNode.isLeaf():
                break

            else:
                pCurNode = self.getNextChild(pCurNode, dValue)
        pCurNode.insertItem(pTempItem)

The very first statement in the insert() isn't doing what it should do. When the control reaches the first statement in the while loop I am encountered with the following error:

AttributeError: 'NoneType' object has no attribute 'isFull'

And if I just replace the first statement within the while loop with this one (just to test):

if self._pRoot.isFull():

It accepts the attribute and moves forward (to raise the same error for other such statements, like the one in elif condition here)

So it's clear here that pCurNode is treated as None type, instead of the fact that I am assigning it to a Node type object using the statement pCurNode = self._pRoot

It's been a couple of hours I am trying to figure it out and still I don't have the slightest idea what's going in here. So decided to ask you fellas. I know there is a something very silly here, that is causing the problem. But can't figure it out.

Can you find the problem here?

Upvotes: 1

Views: 553

Answers (1)

Nikos M.
Nikos M.

Reputation: 8345

(adding comment as answer)

you should check if pCurNode is not None in the while clause like this: while pCurNode: or while pCurNode is not None: this is your problem.

This happens because the loop might not exit in a leaf, and this statement

else:
   pCurNode = self.getNextChild(pCurNode, dValue) 

can fail to find any next child.

Similarly for the other statements where the node can fail to find any next child or parent (thus returning a None-like value).

Finaly before inserting check like this:

if pCurNode and pCurNode.isLeaf():  # insert data here

Upvotes: 4

Related Questions