An error with removeNodeCheckKeepShape_normalizeHandles_

Hi! I have the following code that is supposed to remove the selected nodes and keep shapes:

for item in Layer.selection:
	if not item.parent:
		continue
	item.parent.removeNodeCheckKeepShape_normalizeHandles_(item, True)

If you run it with 1 circle selected, it works as expected, but select 2 circles and it raises this error:

Traceback (most recent call last):
  File "<macro panel>", line 1
  File "_convenience.py", line 152, in <lambda>
    ("__next__", lambda self: container_unwrap(self.nextObject(), StopIteration)),
                                               ^^^^^^^^^^^^^^^^^
IndexError: NSRangeException - *** -[NSArray getObjects:range:]: range {16, 8} extends beyond bounds [0 .. 6]

I get that the iteration breaks somewhere, but can’t figure out what to check to avoid it, any hints please?

What this error is telling you is that the array (in this case: layer.selection) has changed while iterating over it.

Do the following instead:

  • add the items you want to delete to a new Python list
  • after collecting the items, iterate over the items in the list and use that list to remove them from Layer.selection.

Perfect, thank you! I got confused because it works for some arrays but not for others depending on something :slight_smile:

It is never a good idea to iterate over a list that is in any way change in the loop. Removing the node will also remove it from the selection …