-1

I have a recursive class (it has a method that puts an instance of itself in a dict that is a class variable), allowing me to iteratively chain objects together and make a sort of tree structure. I've found that sometimes my data has some circularity to it and in an attempt to avoid getting lost in loops in the data, I'm trying to carry a list of nodes I've been to on the current branch, but things are not working at all as I expected. Consider the following:

class test(object):
    a = 2
    def __init__(self, prevChain):
        self.chain = prevChain
        print("prevChain:", prevChain)
        print("self.chain:", self.chain)
        self.chain.append(self.a)
        print("prevChain:", prevChain)
        print("self.chain:", self.chain)

>>>test([1])
prevChain: [1]
self.chain: [1]
prevChain: [1, 2]
self.chain: [1, 2]
<__main__.test object at 0x00000027CCF1CEB00>

How is the 2 getting added to prevChain and how can I prevent that from happening? Is this the wrong way to go about tracking my location within my recursive objects?

ffollett
  • 15
  • 6
  • 1
    The problem is you only have one list. You just have two references to it. It's a duplicate question (see the above link for the original answer). – Tom Karzes May 26 '19 at 21:37
  • 1
    Mutable objects can have multiple references to themselves. You need to use `prevChain[:]` at least to copy the list. – N Chauhan May 26 '19 at 21:38

1 Answers1

1

In the parameter, prevChain is passed as a reference. So, when you do this-

self.chain = prevChain

you are actually setting the reference of prevChain to self.chain. Thus, prevChain and self.chain are the same variables. To keep them separate, use deepcopy to create a new object of prevChain using the copy lib and then assign it to self.chain.

self.chain = copy.deepcopy(prevChain)
Arshad
  • 218
  • 3
  • 10