-2

Im trying to return a list of test based on a given test. e.g. I have test and it should return a list with two test

I have the following code inside Test

class Test:
    lots = []

    def __init__(self):
        pass

    def add_lot(self, lot):
        self.lots.append(lot)

    def split_test_based_on_needed_restarts(self):
        test_list = []
        test_to_add = Test()
        previous_lot = False
        for index, lot in enumerate(self.lots):
            if previous_lot is not False:
                if self.vp_items_are_different(self.lots[index - 1], lot):
                    test_list.append(test_to_add)
                    test_to_add = Test()
            test_to_add.add_lot(lot)
            previous_lot = lot
        test_list.append(test_to_add)
        return test_list

    def vp_items_are_different(self, param, lot):
        return True


class Lot:
    def __init__(self):
        pass


test = Test()

test.add_lot(Lot())
test.add_lot(Lot())

tests = test.split_test_based_on_needed_restarts()

For some reason the line test_to_add.add_lot(lot) is incresing self.lots making the loop never ending. I thought with test_to_add = Test() I would make a new object. How can I add it to test_to_add and not the self.lots?

Sven van den Boogaart
  • 11,833
  • 21
  • 86
  • 169
  • 1
    "For some reason the line `test_to_add.add_lot(lot)` is incresing `self.lots`" How are we supposed to know that reason without a [mcve]? How are you defining `self.lots`? Perhaps you are using a class variable instead of an instance variable, perhaps you are using a mutable default argument to your constructor. In any case, you must provide a [mcve] – juanpa.arrivillaga Jan 21 '21 at 16:58
  • @juanpa.arrivillaga I updated my code with a working example. – Sven van den Boogaart Jan 21 '21 at 18:09
  • 1
    This is a duplicate of this question: https://stackoverflow.com/questions/1680528/how-to-avoid-having-class-data-shared-among-instances So, yes, you are using a class variable (i.e. a "static") variable, not an instance variable. – juanpa.arrivillaga Jan 21 '21 at 18:35
  • Does this answer your question? [How to avoid having class data shared among instances?](https://stackoverflow.com/questions/1680528/how-to-avoid-having-class-data-shared-among-instances) – Aaron Jan 21 '21 at 18:38

1 Answers1

1

this line: test_to_add.add_lot(lot) in split_test_based_on_needed_restarts continually adds new Test objects inside the loop, Which is why it loops infinitely. Test.lots is a class attribute not an object attribute so lots is a shared list between all Test objects.

Aaron
  • 10,133
  • 1
  • 24
  • 40