# This example assumes we have a mesh object selectedimportbpyimportbmesh# Get the active meshme=bpy.context.object.data# Get a BMesh representationbm=bmesh.new()# create an empty BMeshbm.from_mesh(me)# fill it in from a Mesh# Modify the BMesh, can do anything here...forvinbm.verts:v.co.x+=1.0# Finish up, write the bmesh back to the meshbm.to_mesh(me)bm.free()# free and prevent further access

When explicitly converting from mesh data python owns the data, that is to say - that the mesh only exists while
python holds a reference to it, and the script is responsible for putting it back into a mesh data-block when the edits
are done.

Note that unlike bpy, a BMesh does not necessarily correspond to data in the currently open blend file,
a BMesh can be created, edited and freed without the user ever seeing or having access to it.
Unlike edit mode, the bmesh module can use multiple BMesh instances at once.

Take care when dealing with multiple BMesh instances since the mesh data can use a lot of memory, while a mesh that
python owns will be freed in when the script holds no references to it,
its good practice to call bmesh.types.BMesh.free which will remove all the mesh data immediately and disable
further access.

# in this example the active vertex group index is used,# this is stored in the object, not the BMeshgroup_index=obj.vertex_groups.active_index# only ever one deform weight layerdvert_lay=bm.verts.layers.deform.activeforvertinbm.verts:dvert=vert[dvert_lay]ifgroup_indexindvert:print("Weight %f"%dvert[group_index])else:print("Setting Weight")dvert[group_index]=0.5

As mentioned above, it is possible to create an invalid selection state
(by selecting a state and then de-selecting one of its vertices’s for example), mostly the best way to solve this is to
flush the selection after performing a series of edits. this validates the selection state.