Search code examples
pythonautocaddxfezdxf

Find .dxf entity based on handle with EZDXF library


I've been using the Autocad API to fill out block attributes based on the (pre determined) handle ID. Here is a sample of the implementation:

    frame1 = acad.ActiveDocument.HandleToObject('18CA1')
    frame2 = acad.ActiveDocument.HandleToObject('77CE9')

    frames = [frame1, frame2]


    for i in range(len(frames)):
        for attrib in frames[i].GetAttributes():
            if attrib.TagString == 'DATE':
                attrib.TextString = datasource.date
            if attrib.TagString == 'CLIENT_NAME':
                attrib.TextString = datasource.client_name
            attrib.Update()

Now I want to implement the same functionality using the ezdxf library. I just haven't been able to find a method similar to .HandleToObject("xxx"). Based off the following code I determined that the handle ID's are indeed the same as in the autocad implementation.

modelspace = dxf.modelspace()

for e in modelspace:
    if e.dxftype()== 'TEXT':
        print("text: %s\n" % e.dxf.text)
        print("handle: %s\n" % e.dxf.handle)

Would this be possible in ezdxf? I have made lists of all the specific handles I need to change and ideally I'd rather iterate over that list than having to iterating over all entities to check their handle.


Solution

  • ezdxf stores all entities of a DXF document in the entity database by their handle as key:

    doc = ezdxf.new()
    msp = doc.modelspace()
    p = msp.add_point((0, 0))
    

    Retrieve entities by index operator:

    p1 = doc.entitydb[p.dxf.handle]
    assert p1 is p
    

    This method raises a KeyError if the handle doesn't exist, the get() function returns None if the handle doesn't exist:

    p2 = doc.entitydb.get(p.dxf.handle)
    assert p2 is p
    assert doc.entitydb.get('ABBA') is None