Home/ Reference/ Pitfalls

Do not read a shape after Delete

After Delete, even reading StaticID raises. Wrap traversal bodies in try/except.

Symptom

Do not read a shape after Delete

Notes

After Delete, even reading StaticID raises. Wrap traversal bodies in try/except.

Python example (runnable)

Requires pywin32. The example assumes app / doc / page / layer are already connected. See Connection & Init
Python
page = doc.ActivePage

for i in range(page.Shapes.Count, 0, -1):     # iterate in reverse to delete safely
    s = page.Shapes.Item(i)
    try:
        if s.Name == "temp":
            s.Delete()
    except Exception:
        continue                              # reading a deleted shape raises, so wrap it
print("Cleaned up, remaining: ", page.Shapes.Count)

About this section: Pitfalls

Pitfalls — errors that fail without raising.

Other entries in this section