Sub topic 15
Scripting Extrude and Inset with Python
This chapter shows how to reproduce Extrude Region and Inset Faces from Python. It covers the two ways to do it, the context rules that make scripts fail, and a standalone script that builds a small object with no viewport interaction.
Prerequisites
This chapter assumes you have used the following:
- Extrude Region (E), Inset Faces (I), and the Adjust Last Operation panel in Edit Mode.
- Vertex, edge, and face selection modes.
- The Scripting workspace, with its Text Editor and Python Console.
- Basic Python: functions, list comprehensions, and
isinstance.
Two layers: operators and bmesh
Blender gives you two ways to change a mesh from a script.
Operators live in bpy.ops. Each one is the same command a menu item or key runs. bpy.ops.mesh.inset is the Inset Faces tool. Operators act on the current selection and the current context. They need Edit Mode and a 3D Viewport (or equivalent) context.
bmesh is a data-level API. You load a mesh into a BMesh object and call functions in bmesh.ops on lists of vertices, edges, and faces that you choose. There is no dependence on the viewport or on the selection, unless you read the selection yourself.
| Question | `bpy.ops.mesh.*` | `bmesh` and `bmesh.ops` |
|---|---|---|
| Acts on | The current selection | Geometry you pass in |
| Needs Edit Mode | Yes | No, if you build the BMesh from mesh data |
| Returns | A set such as `{'FINISHED'}` | Dictionaries of new geometry |
| Handling new geometry | You re-read the selection | You get the new elements back |
| Best for | Quick one-off scripts, matching the UI exactly | Loops, generators, and add-ons |
Using the operators
An operator call does what the key press does. This one is Extrude Region followed by a move of 1 unit along Z, the same as pressing E, Z, 1, Enter:
import bpy
# Run with a mesh object active and in Edit Mode, with one or more faces selected.
bpy.ops.mesh.extrude_region_move(
TRANSFORM_OT_translate={"value": (0.0, 0.0, 1.0)}
)extrude_region_move is a macro operator. It runs the extrude and then a translate. The translate settings go in a keyword argument named after the sub-operator, TRANSFORM_OT_translate. The value is the same vector you would type in the Adjust Last Operation panel.
Inset is a plain operator, and its properties match the panel:
import bpy
# Run in Edit Mode with faces selected.
bpy.ops.mesh.inset(thickness=0.1, depth=0.0)The other panel options are also keyword arguments: use_boundary, use_even_offset, use_relative_offset, use_edge_rail, use_outset, use_individual, and use_select_inset. Leaving one out gives its default, which may differ from what you last used in the UI.
Context rules that cause most failures
- Wrong mode. Called from Object Mode, a mesh operator raises
RuntimeError: Operator bpy.ops.mesh.extrude_region_move.poll() failed, context is incorrect. Switch first withbpy.ops.object.mode_set(mode='EDIT'). - Nothing selected. The operator returns
{'FINISHED'}and changes nothing, or changes the wrong thing. Set the selection before the call. - Selection mode. An operator reads the selection through the current select mode. Set it with
bpy.context.tool_settings.mesh_select_mode = (False, False, True)for face mode. - Several objects in Edit Mode. Operators act on every object in Edit Mode, not only the active one.
Using bmesh in Edit Mode
When you want control over the new geometry, load the Edit Mode mesh into a BMesh. The next script extrudes the selected faces, finds the new vertices, and moves only those:
import bpy
import bmesh
obj = bpy.context.edit_object
me = obj.data
bm = bmesh.from_edit_mesh(me)
faces = [f for f in bm.faces if f.select]
ret = bmesh.ops.extrude_face_region(bm, geom=faces)
new_verts = [e for e in ret["geom"] if isinstance(e, bmesh.types.BMVert)]
bmesh.ops.translate(bm, vec=(0.0, 0.0, 1.0), verts=new_verts)
bmesh.update_edit_mesh(me)The working model:
bmesh.from_edit_mesh(me)returns a BMesh that shares data with the Edit Mode mesh. Do not callbm.free()on it.extrude_face_regionreturns a dictionary. Its"geom"list holds every new vertex, edge, and face, so you filter by type withisinstance.translatemoves only the vertices you give it. The extruded top moves, and the side walls stretch to follow.bmesh.update_edit_mesh(me)pushes the change to the viewport. Without it, the data changes but the display and undo history do not update correctly.
If you call a bpy.ops operator in the middle of such a script, re-run bmesh.from_edit_mesh(me) afterwards. The operator rewrites the mesh data, and an older bm variable may point at stale elements.
Building an object with no viewport
Scripts that run in Object Mode, such as add-ons and batch generators, should build the BMesh from scratch. The script below creates a cube, insets its top face, and extrudes the inner face upward. That makes a box with a raised block on its lid:
import bpy
import bmesh
mesh = bpy.data.meshes.new("ScriptedBox")
obj = bpy.data.objects.new("ScriptedBox", mesh)
bpy.context.collection.objects.link(obj)
bm = bmesh.new()
bmesh.ops.create_cube(bm, size=2.0)
bm.faces.ensure_lookup_table()
# Pick the top face: the face whose center is highest on Z.
top = max(bm.faces, key=lambda f: f.calc_center_median().z)
bmesh.ops.inset_region(bm, faces=[top], thickness=0.3, depth=0.0)
# After the inset, the inner face is the largest face that points up.
up_faces = [f for f in bm.faces if f.normal.z > 0.99]
inner = max(up_faces, key=lambda f: f.calc_area())
ret = bmesh.ops.extrude_face_region(bm, geom=[inner])
new_verts = [e for e in ret["geom"] if isinstance(e, bmesh.types.BMVert)]
bmesh.ops.translate(bm, vec=(0.0, 0.0, 1.0), verts=new_verts)
print("faces:", len(bm.faces), "verts:", len(bm.verts))
bm.to_mesh(mesh)
bm.free()
mesh.update()Three details matter here.
- Face selection by property. The script picks faces by position, normal, and area, not by index. Indices change after every operation, so a stored index is unreliable. A geometric test survives edits.
- Normals after an inset.
f.normalis only valid when the normals are up to date.create_cubeand the operators used here set them, so the test works. If you build faces by hand, callbm.normal_update()first. - Cleanup. A BMesh made with
bmesh.new()must be released withbm.free()once you write it back withto_mesh. Forgetting this leaks memory in long-running scripts.
Inset and extrude options in bmesh
bmesh.ops.inset_region takes the same options as the operator, with slightly different names:
| Operator property | `inset_region` argument |
|---|---|
| `thickness`, `depth` | `thickness`, `depth` |
| `use_boundary` | `use_boundary` |
| `use_even_offset` | `use_even_offset` |
| `use_relative_offset` | `use_relative_offset` |
| `use_edge_rail` | `use_edge_rail` |
| `use_outset` | `use_outset` |
| `use_individual` | Call `bmesh.ops.inset_individual` instead |
Extrude Individual Faces has its own function, bmesh.ops.extrude_discrete_faces. It extrudes each face on its own, so neighboring faces do not share new edges.
Common errors
poll() failed, context is incorrect. The operator was called outside Edit Mode, or from a context with no 3D Viewport. Fix the mode, or use bmesh.- The script runs and nothing moves. The selection was empty, or
bmesh.update_edit_mesh(me)was never called. - Extruded geometry stays in place. You translated the wrong list. Move only the new vertices from
ret["geom"], not the original selection. - Duplicate geometry. Running the script twice on the same selection extrudes twice. The first extrude leaves the new faces selected, so the second extrudes those faces again and stacks a second layer on the first.
- Crash or garbage after
free(). Callingbm.free()on a BMesh fromfrom_edit_meshinvalidates Blender's own data. Free only BMeshes created withbmesh.new()orbmesh.from_mesh().
Exercise
A script in Object Mode calls bpy.ops.mesh.inset(thickness=0.1) and fails with "poll() failed, context is incorrect". Give two ways to fix it, and say which one suits an add-on that generates many objects.
Show answer
Fix 1: switch to Edit Mode first with bpy.ops.object.modeset(mode='EDIT'), select the faces, then call the operator. Fix 2: skip the operator and use bmesh. Load the mesh with bmesh.new() and bm.frommesh(mesh), call bmesh.ops.insetregion with the faces you choose, then write back with bm.tomesh(mesh) and bm.free(). Fix 2 suits the add-on because it needs no mode switch and no selection, and it returns the new geometry.
Exercise
In the Edit Mode bmesh script, what happens if you leave out bmesh.updateeditmesh(me), and why must you filter ret["geom"] with isinstance before translating?
Show answer
Without updateeditmesh, the viewport and undo system are not told about the change, so the display may not refresh and the edit can be lost. ret["geom"] contains new vertices, edges, and faces together. bmesh.ops.translate accepts only vertices in its verts argument, so you keep the BMVert items with isinstance(e, bmesh.types.BMVert).