GHPython component mysteriously changing list data from class?


(P1r4t3b0y) #1

Hello folks,

Let’s say I have the following code inside a GHPython component:

import Rhino.Geometry as rg
import random

TIME = 100

class MyClass:
    def __init__(self):
       self.my_list = []
    def update(self):
        pt = rg.Point3d(random.random(), random.random(), random.random())

mc = MyClass()

time_list = []

for t in range(TIME): # moment in time
    print mc.my_list

a = time_list

The goal is to output the list of lists time_list, which includes a list of points, provided by the class MyClass for each moment in time. I have no problems converting the nested list to a tree, but my issue lies with how the component runs, at least I believe so.

If I output the nested list, all of its sublists are already populated with a TIME-number of points (here 100).
However, what I want is an increasing number of points per sublist over time. For example, at the first iteration of the for loop, only one point should be in the first sublist, than 2 points, after that 3, … and 100 points at iteration TIME-1 (here 99).

This way I want to keep track of what happens at each moment in time. Furthermore, I could probably animate the process by looping through the tree branches with a Timer and Counter combo.

I guess my problem stems from the refresh rate of the component itself, or something like that. When I print mc.m_list inside the for loop, just before appending it to the time_list, the printed output shows the right result (i-number of points per sublist). However, the sublists of the time_list after the for loop, all have TIME-number of points inside (here 100). How can that even be?

(Graham) #2

Hi this is a classic Python problem: you are not adding a copy of your list each time , you are adding a reference to your list. See this stackoverflow post for a range of possible solutions:

(P1r4t3b0y) #3

Thanks @Dancergraham! I did not know that about Python lists. Now it works.