Search code examples
pythonarraysdebuggingnonetype

printing the values of an Array prevents a null pointer error


I'm trying to search a parameter space for a good model. In my code I'm doing something like the following:

configurations = [None] * 9
index = 0
for param1 in range(3):
  for param2 in range (3):
    #call constructor
    configurations[index] = Configuration(param1, param2) 
    index = index + 1
return configurations

then I use this array elsewhere to build the models. However, for some reason it doesn't fill the array. I get an error when accessing index 3 or higher. Inspection shows that the array at these indices are still 'None'. while debugging this, I added a print statement to the code:

configurations = [None] * 9
index = 0
for param1 in range(3):
  for param2 in range (3):
    #call constructor
    configurations[index] = Configuration(param1, param2)
    index = index + 1

for x in configurations:
  print(x.param1)
return configurations

to my surprise, my code now ran smoothly. The array is completely filled. If I comment out those 2 lines: error. uncomment the lines: it works again.

what is going on here? Why is the print statement altering the behavior of my program? is this an overactive GC that's staved off by printing the values?


Solution

  • I found the issue. the return statement was indented with a Tab, but I use 4 spaces everywhere else in my code. This was causing it to skip the most outer for loop. the print statement somehow prevented this. changing the tab to spaces removed the need for the print statement.