Search code examples
pythonpython-3.xoopnonetype

How to make all the reference variables None in Python?


I got a typical ListNode class something like below,

class ListNode:
    def __init__(self,val, next = None):
        self.val = val
        self.next = next

I created two instances of this class, and assigned one of the object to a variable called next in first instance as below,

node = ListNode(1)
next_node = ListNode(2)
node.next = next_node

However, if I assign nnode = None, the node.next still points to the instance next_node and is not None.

print( next_node == node.next) # Prints True
next_node = None
print( node.next.val) # Prints 1

How can I make all the reference variables (e.g. node.next in above case) make None without explicitly assigning them to None?


Solution

  • I really like your question. Probably this is not exactly what you are looking for, but I have found weakref library. With it you could try to modify your code:

    class ListNode:
        def __init__(self, val, next_=None):
            self.val = val
            self.next_ = next_
    
        def get_next(self):
            try:
                self.next_.check()
            except AttributeError: # if self.next_ exists then it does not have 'check' method.
                return self.next_
            except ReferenceError: # if it does not exists it will raise this exception
                return None
    

    Then instead of assigning node.next_ = next_node, you can create weakref:

    node = ListNode(1)
    next_node = ListNode(2)
    node.next_ = weakref.proxy(next_node)
    
    print( next_node == node.next_) # prints True
    next_node = None
    print(node.get_next()) # prints None
    

    Hope this will help solve your problem!

    Edit: I have also changed the name next to next_ because next is a builtin function