How to delete anchor via script?

Font = Glyphs.font
selectedLayers = Font.selectedLayers

print "Deleting anchors in:"

delList=[]

for thisLayer in selectedLayers:
	thisGlyph = thisLayer.parent
	print "-- %s" % thisGlyph.name
	for i, anchor in enumerate(thisLayer.anchors):
		if anchor.name in ["bottom_1_2", "bottom_2_2"]:
			delList += [i]
	thisGlyph.beginUndo()
	for i in delList:
		del thisLayer.anchors[i]
	thisGlyph.endUndo()

Doesn’t work, I get a type error. Nothing happens for this either:

for thisLayer in selectedLayers:
    	thisGlyph = thisLayer.parent
    	print "-- %s" % thisGlyph.name
    	for anchor in thisLayer.anchors:
    		if anchor.name in ["bottom_1_2", "bottom_2_2"]:
    			del anchor
    print delList

the anchor property is a dictionary. So you need to use the name as a key.

del(thisLayer.anchors[anchorName])

This is a bit confusing. del(thisLayer.anchors[anchor.name]) still throws a TypeError when I try it.

Also, print thisLayer.anchors gives me something that looks like tuple, which explains why for anchor in thisLayer.anchors gives anchors, not dictionary keys. Is the anchor property really a dictionary?

can you try del(thisLayer.anchors[str(anchor.name)])

I’ll fix this.

This works now.

It is a bad idea to delete items of a collection while you’re iterating over it. Better iterate over a reverse (from biggest to smallest number) list of indexes.

Do you mean something like:

for thisLayer in selectedLayers:
	thisGlyph = thisLayer.parent
	print "Deleting anchors in %s:" % thisGlyph.name
	delList = []
	for anchor in thisLayer.anchors:
		anchorName = str(anchor.name)
		if searchFor in anchorName:
			delList += [anchorName]
	for anchor in delList:
		print "\tDeleting %s" % anchor
		thisGlyph.beginUndo()
		del(thisLayer.anchors[anchor])
		thisGlyph.endUndo()

And what’s the significance of the reverse? And why indexes–which doesn’t work as per above, and not by the str(anchor.name)?

It is ave if you first collect all the anchor names that you like to remove in an extra array.

Sorry, I meant this part. It is going through the actual anchors and potentially deleting some of them.

You do not mess up the indexes of the list if you first delete the item 5, then item 3. If you first delete item 3, then item 5 could suddenly be out of range already.