Exception Access Violation when trying to add face to new Facemap

Beginner Python scripter here, upon running my operator Blender crashes, inspecting the crashlog just yields an EAV as described. The crash appears to happen at the "facemaps[x-1].add(face)" line. I haven't been able to find much information about the new facemaps so have only been going off what I found on other similar properties.

I cannot use vertex groups as an alternative as during subdivisions they blend out into other vertices which is not ideal for my purposes.

   def execute(self, context):
obj = bpy.context.edit_object
me = obj.data
bmsh = bmesh.from_edit_mesh(me)

verts = []
facemaps = []
face = [0]

x = 1

for f in bmsh.faces:
for v in f.verts:
verts.append(v.co)

face[0] = f.index
facemaps.append(obj.face_maps.new( name = str(x)))
bpy.ops.object.editmode_toggle()
bpy.ops.object.editmode_toggle()
x = x + 1


Perhaps the cause of the crash was accessing an invalid reference.

>>> import bmesh
>>> obj = bpy.context.edit_object
>>> me = obj.data
>>> bmsh = bmesh.from_edit_mesh(me)
>>> bmsh.faces
<BMFaceSeq object at 0x000002686604A600>

>>> bpy.ops.object.editmode_toggle()
{'FINISHED'}

>>> bpy.ops.object.editmode_toggle()
{'FINISHED'}

>>> bmsh.faces
Traceback (most recent call last):
File "<blender_console>", line 1, in <module>
ReferenceError: BMesh data of type BMesh has been removed


The following script is based on the examples in API documents.

def execute(self, context):
obj = bpy.context.edit_object
me = obj.data
bmsh = bmesh.from_edit_mesh(me)
fm_lay = bmsh.faces.layers.face_map.active

for f in bmsh.faces:

fm = obj.face_maps.new( name=str(f.inded+1) )
f[fm_lay] = fm.index

• After integrating this into the script, it works, but very inconsistently, and I can't figure why. More often it throws AttributeError: BMElem[key]: invalid key, must be a BMLayerItem on the f[fm_lay] = fm.index line. Dec 26 '20 at 7:39
• I'm thinking there must be some context stuff going on, I'm in edit mode and need to have some number of faces selected that will be used later in the script. Dec 26 '20 at 7:50
• @MykhailKozak did you ever resolve this? I've been looking for code snippets for creating new face maps and assigning faces to them, but I can't for the life of me figure it out. Sep 30 '21 at 13:46
• @DrewTNBD Unfortunately not, I ended up stopping the script since someone came out with a plugin that gave the result I wanted but achieved it in a very different manner than how I was attempting. Oct 2 '21 at 1:20
• @MykhailKozak I managed to figure out my problem: gist.github.com/DrewTNBD/1ad1f26c25afbe3e843e958fa7851680 You would need to customize it for your own needs. But essentially: Ensure look-up for faces and verts. Verify the facemap layers. For each face, set the new index. Oct 3 '21 at 11:36