0

My recursive function does not work as expected. After some debugging I found that after I put object to dictionary, it's member gets modified.

I.e. this code

package: Package = Package(name)
print(f'package.children: {package.children}')
nodes[name] = package
print(f'package.children: {package.children}')

produces the output:

package.children: {}
package.children: {'b': <primitives.Package object at 0x7f54d0c94d30>}

Here is the definition of Package:

Nodes = Dict[ShortName, Node]

class Package(Node):
  children: Nodes = dict({})

  def __init__(self, short_name: ShortName):
    super().__init__(short_name)

This is the full method body:

def _insert_element(nodes: Nodes, element: Element, path: List[ShortName]):
  name: str = path[0]
  if len(path) == 1:
    nodes[element.short_name] = element
  else:
    package: Package = Package(name)
    nodes[name] = package
    print(f'package.children: {package.children}')
    _insert_element(package.children, element, path[1:])

How can it be?

MisterMiyagi
  • 44,374
  • 10
  • 104
  • 119
polina-c
  • 6,245
  • 5
  • 25
  • 36

1 Answers1

0

I found what was the issue: the member Package.children was class member, not instance member.

I moved declaration and initialization of children from class to __init__ and it solved the problem:

class Package(Node):
  
  def __init__(self, short_name: ShortName):
    super().__init__(short_name)
    self.children = {}

See more in this post.

polina-c
  • 6,245
  • 5
  • 25
  • 36