0

I am trying to get the children list in text format from my Node class. I need this to be able to print the structure in JSON format.

When I am trying to call the getchildren() method or directly use the same code in __str__, in both cases I get a max recursion error. It comes with 'Above line was executed 196 times'.

I got some solutions saying increase this limit, that may solve my problem and I will try that if nothing else works, but am not able to get why am I getting this error.

It is something like I am trying to create a JSON of something that was supposed to be an XML so its quite nested and the source is a CSV file, the code shows a single Node of data.

Am pretty new to Python and stuff like this works well in Java so confused.

I have this code:

class Node:
    _attributeDictionary = {}
    _lst = []

    def __init__(self, tag):
        self._tag = tag

    def setAttribute(self, attributeName, attributeValue):
        self._attributeDictionary [attributeName]= attributeValue

    def setChild(self, node):
        self._lst.append(node)

    def getchildren(self):
        s = "["
        for l in self._lst:
            s = s + str(l) + "],"
        return s[:-1]

    def __str__(self):
        s = "["
        for l in self._lst:
            s = s + str(l) + "],"
        return "'" + self._tag + "':" + str(self._attributeDictionary) + "," + s[:-1] + ""


nodeA=Node("A")
nodeA.setAttribute("attA","valA")
nodeB=Node("B")
nodeB.setAttribute("attA","valB")
nodeA.setChild(nodeB)
print(str(nodeA))

Error:

s = s + str(l) + "],"
[Previous line repeated 196 more times]
RecursionError: maximum recursion depth exceeded
MagicBeans
  • 343
  • 1
  • 5
  • 18
  • 1
    If you want to print in JSON format, why are you putting single quotes around the tag instead of double quotes? – Barmar May 23 '19 at 19:17
  • Also, in JSON an object should be surrounded by `{}` not `[]`. – Barmar May 23 '19 at 19:17
  • Shouldn't `setAttribute()` add a new attribute to the dictionary, not replace the entire dictionary with just one attribute? – Barmar May 23 '19 at 19:23
  • 1
    E.g. `self._attributeDictionary[attributeName] = attributeValue` – Barmar May 23 '19 at 19:24
  • Thanks for pointing all this out. Noted. This is dummy code a lot needs to be refined but need to solve the recursion error .Is there a solution recursion error? – MagicBeans May 24 '19 at 01:55
  • 1
    The problem is that all your nodes are using the same `_list` variable. So every node is a child of itself. – Barmar May 24 '19 at 01:59
  • That's why it was linked to that duplicate. – Barmar May 24 '19 at 02:00
  • Thanks go the answer. The variables lst and dictionary should be declared inside __init__() – MagicBeans May 24 '19 at 03:46

0 Answers0