Sub topic 16
Automating booleans and cleanup with Python
This chapter assumes you can already apply a Boolean modifier by hand, clean a mesh with Merge by Distance and Recalculate Normals, and open Blender's Scripting workspace. You do not need prior Python experience beyond reading short scripts. The goal is to turn the manual workflow from earlier chapters into a repeatable script.
Why script a boolean workflow
A boolean setup involves the same steps each time: add a modifier, set its operation and solver, point it at a cutter, hide the cutter, apply the result, then clean the mesh. Scripting these steps has three benefits.
- You get the same settings on every object, so results do not depend on what you remembered to click.
- You can process many objects in one run.
- You can print diagnostics, such as how many non-manifold edges remain, instead of checking by eye.
Two Blender APIs do the work here. bpy is the main Python module. It gives access to objects, modifiers and operators. bmesh is a module for editing mesh geometry directly in memory, with functions for merging vertices, deleting geometry and testing edges.
The overall pipeline
The script has three stages. Each stage maps to a concept from earlier in the tutorial.
Stage 1: Add the Boolean modifier
The first script adds a Boolean modifier to the active object. It uses the object named Cutter as the operand, which is the object that does the cutting.
import bpy
target = bpy.context.active_object
cutter = bpy.data.objects["Cutter"]
mod = target.modifiers.new(name="Boolean", type='BOOLEAN')
mod.operation = 'DIFFERENCE'
mod.operand_type = 'OBJECT'
mod.object = cutter
mod.solver = 'EXACT'
cutter.display_type = 'WIRE'
cutter.hide_render = TrueHere is what each line does.
target.modifiers.new(...)creates the modifier and returns it. Thenameis the label you see in the modifier stack. You will need that label later when you apply it.mod.operationaccepts'DIFFERENCE','UNION'or'INTERSECT'. These match the three operations covered earlier.mod.operand_type = 'OBJECT'means the cutter is a single object. The other value,'COLLECTION', uses every object in a collection.mod.solveraccepts'EXACT'or'FAST'. Exact is slower but handles overlapping and coplanar geometry more reliably.cutter.display_type = 'WIRE'shows the cutter as a wireframe in the viewport, so you can see the target through it.cutter.hide_render = Truekeeps the cutter out of final renders.
The script sets properties but does not change the mesh. The cut is only a live preview until you apply the modifier. This is the non-destructive part of the cutter workflow.
Common errors at this stage
| Symptom | Likely cause |
|---|---|
| `KeyError: 'bpy_prop_collection[key]: key "Cutter" not found'` | No object has that exact name. Names are case sensitive. |
| `AttributeError: 'NoneType' object has no attribute 'modifiers'` | There is no active object. Click an object in the viewport first. |
| `TypeError` when creating the modifier | The active object cannot hold modifiers, for example an empty or a camera. |
| Cut looks wrong, or nothing appears | Scale is not applied on the target or cutter, or the cutter is not manifold. See the preparation chapter. |
Stage 2: Apply the modifier
Applying the modifier bakes the cut into the mesh data. Afterwards the cutter is no longer needed for the result, though you may want to keep it for later edits.
import bpy
target = bpy.context.active_object
with bpy.context.temp_override(object=target, active_object=target):
bpy.ops.object.modifier_apply(modifier="Boolean")bpy.ops.object.modifier_apply is an operator. Operators act on the current context, which means the active object and the current mode. They fail if the context is wrong. The temp_override block sets the context for the duration of the with statement, so the operator acts on target even when you run the script from the Text Editor.
Keep these points in mind.
- The
modifierargument is the modifier's name, not its type. If you named it something other than"Boolean", use that name. - Order matters. Applying a modifier that is not first in the stack gives a warning, because modifiers above it change the input the boolean saw. Apply from the top down, or reorder the stack first.
- The object must be in Object Mode. Applying in Edit Mode fails.
- A mesh shared by several objects (linked duplicates) cannot be applied without first making it single-user. Blender reports an error for this case.
Stage 3: Clean the result with bmesh
A boolean often leaves duplicate vertices along the cut, loose vertices with no edges, and inconsistent normals. The bmesh module can fix all three in one pass.
import bpy
import bmesh
obj = bpy.context.active_object
bm = bmesh.new()
bm.from_mesh(obj.data)
bmesh.ops.remove_doubles(bm, verts=bm.verts, dist=0.0001)
loose = [v for v in bm.verts if not v.link_edges]
bmesh.ops.delete(bm, geom=loose, context='VERTS')
bmesh.ops.recalc_face_normals(bm, faces=bm.faces)
bad_edges = [e for e in bm.edges if not e.is_manifold]
print(f"Non-manifold edges remaining: {len(bad_edges)}")
bm.to_mesh(obj.data)
bm.free()
obj.data.update()The script follows a fixed lifecycle: create a BMesh, load mesh data, edit, write back, free.
bmesh.new()creates an empty BMesh.bm.from_mesh(obj.data)copies the object's mesh into it.remove_doublesis the scripted equivalent of Merge by Distance. Vertices closer together thandist(here 0.0001 units) are merged into one.- The list comprehension finds vertices whose
link_edgescollection is empty. These are loose vertices.bmesh.ops.deleteremoves them. Thecontext='VERTS'argument tells the operator that the input is vertices, so only those vertices are deleted. recalc_face_normalsmakes face normals point consistently outward, like Recalculate Normals in Edit Mode.e.is_manifoldisTruefor an edge shared by exactly two faces. Counting the edges where it isFalsegives a quick pass/fail test for a watertight mesh.bm.to_mesh(obj.data)writes the changes back.bm.free()releases the BMesh memory.obj.data.update()tells Blender to refresh the mesh.
Note that this script works in Object Mode. If you run it while in Edit Mode, the mesh data is not up to date and your changes can be lost. Switch to Object Mode first.
Choosing the merge distance
The dist value is a trade-off. If it is too small, near-duplicate vertices survive and edges stay non-manifold. If it is too large, it collapses real detail, such as the corners of small bevels. Start at 0.0001 for objects around one unit in size. Scale the value with your object. A model measured in millimetres needs a different distance than one measured in metres.
Combining the stages in one function
Placing the stages in one function lets you reuse them and check the result.
import bpy
import bmesh
def boolean_cut(target, cutter, solver='EXACT', merge_dist=0.0001):
"""Cut `cutter` out of `target`, clean the result, return the
number of non-manifold edges left."""
mod = target.modifiers.new(name="Boolean", type='BOOLEAN')
mod.operation = 'DIFFERENCE'
mod.operand_type = 'OBJECT'
mod.object = cutter
mod.solver = solver
with bpy.context.temp_override(object=target, active_object=target):
bpy.ops.object.modifier_apply(modifier=mod.name)
bm = bmesh.new()
bm.from_mesh(target.data)
bmesh.ops.remove_doubles(bm, verts=bm.verts, dist=merge_dist)
loose = [v for v in bm.verts if not v.link_edges]
bmesh.ops.delete(bm, geom=loose, context='VERTS')
bmesh.ops.recalc_face_normals(bm, faces=bm.faces)
bad = sum(1 for e in bm.edges if not e.is_manifold)
bm.to_mesh(target.data)
bm.free()
target.data.update()
return bad
target = bpy.context.active_object
cutter = bpy.data.objects["Cutter"]
remaining = boolean_cut(target, cutter)
print(f"Non-manifold edges remaining: {remaining}")Using mod.name in the apply call avoids hard-coding the name. If the target already has a modifier called "Boolean", Blender renames the new one to "Boolean.001", and mod.name still refers to the right modifier.
Limits of the scripted approach
Scripts automate steps. They do not make a bad input good.
- The script does not apply object scale. A non-uniform scale on the target still produces stretched results, so apply scale before the cut.
- A nonzero count of non-manifold edges means the mesh needs inspection. Open Edit Mode, use Select Non Manifold, and decide whether to fill holes by hand or fall back to Remesh.
- The Fast solver may return wrong geometry on overlapping or coplanar input without raising any error. Always check the count after using it.
- A script cannot judge shading. Smooth shading and sharp edges still need a visual check after the cut.
Exercises
Exercise
A script calls bpy.ops.object.modifier_apply(modifier="Boolean") and Blender reports that the operator cannot run. The target is in Edit Mode. What fix do you make, and why?
Show answer
Switch the object to Object Mode before applying, for example with bpy.ops.object.mode_set(mode='OBJECT'). The modifier_apply operator only works in Object Mode, because the mesh data in Edit Mode is held in an edit buffer that is not yet written back to the object.
Exercise
After the cleanup pass, the script prints "Non-manifold edges remaining: 12". Name two likely causes and one next step.
Show answer
Likely causes include open holes left by a cutter that was not watertight, and coplanar faces that the solver could not resolve cleanly. The Fast solver on overlapping input can also leave gaps. A next step is to open Edit Mode, run Select Non Manifold, and inspect the selected edges. Fill holes with Fill (F), or fall back to Remesh if the mesh is too damaged.
Exercise
Why does the boolean_cut function use mod.name instead of the literal string "Boolean" when it applies the modifier?
Show answer
If the object already has a modifier named "Boolean", Blender gives the new one a different name, such as "Boolean.001". Using mod.name always applies the modifier the function just created.