How to store and later restore mesh select mode?

Hi, I want to store the mesh select mode at the beginning of my script, then select some vertices via python (managed to do that), and then restore the select mode at the end. How to do that? I tried:

SELECTMODE = context.tool_settings.mesh_select_mode

and at the end

bpy.context.tool_settings.mesh_select_mode = SELECTMODE

but that does not work. Also when I switch the select mode manually after the script ran, I lose my newly selected parts. The vertex selection does not convert to edge/face selection.

Any help greatly appreciated.

you’re doing it right, just one thing:

SELECTMODE = context.tool_settings.mesh_select_mode creates a reference to mesh_select_mode, and as you change it with python, SELECTMODE will always give you exactly that, the current state. So if you re-assign it, there’s of course no change.

You need to copy the values:

SELECTMODE = context.tool_settings.mesh_select_mode[:]

Losing selections may happen with bmesh module, you need to manually flush some stuff. But if you do
ob.data.vertices[n].select = True
then there should be no problem, only if you switch from vertex to edge/face selection mode, edges/faces with not all verts selected won’t get selected and parts of your original selection get lost due to this.

Thanks! Works perfect.

Maybe you also know this one - I know how to select all vertices in certain area, I do it like this:

OBJECT = bpy.context.active_object
ODATA = bmesh.from_edit_mesh(OBJECT.data)

for VERTICES in ODATA.verts[:]:
if VERTICES.co[2] > 10000:
VERTICES.select = 1

This select all vertices with z greater than 10000. Now, how to do a similar thing with edges and faces?

maybe like this?

>>> for f in bm.faces:
...     for v in f.verts:
...         f.select_set(v.co.z > 0)

select_set will select verts and edges of selected faces as well

note that every face will get selected, which has at least 1 vert > 0

if you wanna select faces only if all verts are inside the selection, i suggest to use the border select operator.

store
sel_mode = bpy.context.tool_settings.mesh_select_mode[:]
restore
bpy.context.tool_settings.mesh_select_mode = sel_mode

1 Like