Delete Layouts and Blocks

Modelspace

This is not possible.

Paperspace Layouts

Delete a paperspace layout and it’s entities.

name = "MyLayout"
try:
    doc.layouts.delete(name)
except ezdxf.DXFKeyError:
    print(f"layout '{name}' not found")
except ezdxf.DXFValueError:
    print(f"layout '{name}' cannot be deleted")
    # modelspace or last remaining paperspace layout

Block Definitions

Delete a block definition:

try:
    doc.blocks.delete_block(name, safe=True)
except ezdxf.DXFBlockInUseError:
    print(f"cannot delete block '{name}'")

Raises a DXFBlockInUseError exception if the block is referenced by an INSERT entity or if it is an anonymous/special block.

Purge/delete unused (unreferenced) block definitions:

Added in version 1.3.5.

from ezdxf import blkrefs

...

for name in blkrefs.find_unreferenced_blocks(doc)
    doc.blocks.delete_block(name, safe=False)