Sub topic 14
Adding the same modifiers with a Python script
This chapter assumes you can open Blender's Scripting workspace and run a script from the Text Editor. It also assumes you know the four modifiers from earlier chapters: Mirror, Array, Subdivision Surface, and Solidify. The goal is to build the same stack with code, so you can repeat it on many objects or reproduce it exactly.
How a modifier maps to Python
Every object has a collection called obj.modifiers. You add a modifier by calling obj.modifiers.new(name, type). The type is an uppercase string: 'MIRROR', 'ARRAY', 'SOLIDIFY', or 'SUBSURF'. The call returns the new modifier, and each setting you see in the Properties editor is an attribute on that returned object.
Two facts shape everything else in the chapter:
modifiers.newalways appends to the bottom of the stack. The order of your calls is the order of evaluation.- The
nameis only a label. Blender makes it unique on that object by adding a suffix such as.001, so don't assume the name you passed is the name you got. Keep the returned object instead of looking the modifier up by name.
Mirror
This script mirrors across the X axis, clips vertices at the mirror plane, and merges vertices closer than 0.001 units.
import bpy
obj = bpy.context.active_object
mirror = obj.modifiers.new(name="Mirror", type='MIRROR')
mirror.use_axis[0] = True
mirror.use_clip = True
mirror.use_mirror_merge = True
mirror.merge_threshold = 0.001use_axis is a list of three booleans for X, Y, and Z. You set one element at a time, as shown. use_clip stops vertices from moving across the mirror plane in Edit Mode, and use_mirror_merge with merge_threshold welds vertices that sit on the plane.
Two related settings are worth knowing:
use_bisect_axis[0] = Truecuts away geometry on the far side of the plane before mirroring.use_bisect_flip_axis[0] = Truechooses which side is removed.mirror_objecttakes another object. The mirror plane then passes through that object's origin instead of the mesh's own origin.
Array
This script makes five copies in a row along X, each spaced 1.1 object widths from the previous one.
import bpy
obj = bpy.context.active_object
arr = obj.modifiers.new(name="Array", type='ARRAY')
arr.fit_type = 'FIXED_COUNT'
arr.count = 5
arr.use_relative_offset = True
arr.relative_offset_displace[0] = 1.1
arr.use_merge_vertices = FalseThe count includes the original, so the result is five objects, not six. The value 1.1 is relative to the object's bounding box width, which leaves a 10 percent gap.
The other offset modes and fit types from earlier chapters have matching attributes:
| Chapter topic | Python attribute |
|---|---|
| Constant offset | `use_constant_offset`, `constant_offset_displace` (a vector in scene units) |
| Object offset | `use_object_offset`, `offset_object` |
| Fit length | `fit_type = 'FIT_LENGTH'`, `fit_length` |
| Fit curve | `fit_type = 'FIT_CURVE'`, `curve` |
| Start and end caps | `start_cap`, `end_cap` (mesh objects) |
| Merging | `use_merge_vertices`, `merge_threshold` |
You can enable several offset modes at once, and Blender adds their effects together.
Solidify and Subdivision Surface
This script adds Solidify first and Subdivision Surface after it, so the shell is created before smoothing. The viewport level is 1 and the render level is 2.
import bpy
obj = bpy.context.active_object
solid = obj.modifiers.new(name="Solidify", type='SOLIDIFY')
solid.thickness = 0.05
solid.offset = -1.0
solid.use_even_offset = True
subsurf = obj.modifiers.new(name="Subdivision", type='SUBSURF')
subsurf.levels = 1
subsurf.render_levels = 2An offset of -1.0 grows the shell inward, against the normals. A value of 1.0 grows it outward, and 0.0 centers it on the original surface. If the shell grows the wrong way, check the face normals first, then change the sign of offset.
levels is the viewport level and render_levels is the level used for final renders. Keeping the viewport level lower keeps the scene responsive. Blender 2.9 and later also stores a separate quality value, but the default is fine for most work.
A reusable helper and the full stack
Setting attributes one line at a time gets repetitive. A small helper that accepts keyword arguments keeps scripts short. Indexed properties such as use_axis[0] can't be set through keywords, so the helper handles ordinary attributes only and you set the indexed ones afterward.
import bpy
def add_modifier(obj, name, mod_type, **settings):
"""Append a modifier to obj and apply the given attribute values."""
mod = obj.modifiers.new(name=name, type=mod_type)
for attr, value in settings.items():
setattr(mod, attr, value)
return mod
obj = bpy.context.active_object
if obj is None or obj.type != 'MESH':
raise RuntimeError("Select a mesh object first.")
mirror = add_modifier(
obj, "Mirror", 'MIRROR',
use_clip=True,
use_mirror_merge=True,
merge_threshold=0.001,
)
mirror.use_axis[0] = True
arr = add_modifier(
obj, "Array", 'ARRAY',
fit_type='FIXED_COUNT',
count=3,
use_relative_offset=True,
)
arr.relative_offset_displace[0] = 1.1
add_modifier(
obj, "Solidify", 'SOLIDIFY',
thickness=0.05,
offset=-1.0,
use_even_offset=True,
)
add_modifier(
obj, "Subdivision", 'SUBSURF',
levels=1,
render_levels=2,
)
print([m.name for m in obj.modifiers])The stack order here is Mirror, Array, Solidify, Subdivision Surface. This is the workflow order from the earlier chapters. The symmetry and repetition happen first, thickness comes next, and smoothing runs last, so it rounds the finished shell.
The check at the top matters. bpy.context.active_object is None when nothing is active, and a mesh-only modifier such as Solidify is not available on every object type. Failing early with a clear message is easier to debug than an AttributeError three lines later.
Reordering, toggling, and removing
Because new modifiers always land at the bottom, you sometimes need to move one. Use the collection's move method (Blender 2.90 and later):
import bpy
obj = bpy.context.active_object
# Move the last modifier to the top of the stack.
last = len(obj.modifiers) - 1
obj.modifiers.move(last, 0)
# Show or hide a modifier without deleting it.
for mod in obj.modifiers:
if mod.type == 'SUBSURF':
mod.show_viewport = False # hide in the viewport
mod.show_render = True # keep it for renders
# Remove a modifier by reference.
array_mods = [m for m in obj.modifiers if m.type == 'ARRAY']
for mod in array_mods:
obj.modifiers.remove(mod)Filtering on mod.type is more reliable than filtering on mod.name, because names can be changed by the user or carry suffixes. Collect the matches into a list before removing, as shown, so you don't change the collection while iterating over it.
Applying and inspecting the result
A script can apply a modifier the same way the Apply command does. This uses an operator, so it needs the right object in context. From Blender 3.2 you supply that with temp_override:
import bpy
obj = bpy.context.active_object
with bpy.context.temp_override(object=obj, active_object=obj):
bpy.ops.object.modifier_apply(modifier="Mirror")Applying has the same consequences as in the interface. The modifier's effect becomes real mesh data and the modifier disappears. Applying a modifier that is not first in the stack also ignores the modifiers above it, and Blender warns about this. The operator fails on a mesh shared by several objects with the error "Modifiers cannot be applied to multi-user data". Make the data single-user first.
Often you don't need to apply at all. If you only want to know what the stack produces, read the evaluated mesh and leave the modifiers live:
import bpy
obj = bpy.context.active_object
depsgraph = bpy.context.evaluated_depsgraph_get()
eval_obj = obj.evaluated_get(depsgraph)
mesh = eval_obj.to_mesh()
print("Base vertices: ", len(obj.data.vertices))
print("Evaluated vertices:", len(mesh.vertices))
eval_obj.to_mesh_clear()Call to_mesh_clear() when you finish. It frees the temporary mesh that to_mesh() created.
Common errors
TypeError: enum "..." not found: the type or fit type string is wrong. Types must be uppercase and exact, for example'SUBSURF', not'SUBDIVISION'.AttributeErroron a setting: the attribute name differs from the label in the interface. For example, "Merge" on Mirror isuse_mirror_merge, and "Merge" on Array isuse_merge_vertices. Hover over a field and look at the Python tooltip, which needs Python Tooltips enabled in Preferences, or use the Python console's autocomplete.- Modifiers in the wrong order: remember that calls append. Add them in the order you want, or use
modifiers.move. - Duplicate modifiers after running a script twice: each run adds another set. Remove existing modifiers of that type first, or check
obj.modifiers.get(name)before adding. - Operator errors such as "context is incorrect":
bpy.opscalls depend on the current context. Prefer direct property access, and usetemp_overrideonly when an operator is the only option.
Exercises
Exercise
You run a script that calls obj.modifiers.new for Subdivision Surface, then for Solidify. What is wrong with the result, and how do you fix it without deleting either modifier?
Show answer
The stack is Subdivision Surface above Solidify, so the mesh is smoothed first and the thickness shell is built from the smoothed surface. To get the shell created before smoothing, move Solidify to the top with obj.modifiers.move(1, 0), where 1 is Solidify's current index and 0 is the target index.
Exercise
Write the three lines that add an Array modifier with 4 copies and a constant offset of 2 units along Y, with relative offset turned off.
Show answer
arr = obj.modifiers.new(name="Array", type='ARRAY'); then arr.count = 4, arr.userelativeoffset = False. Finally enable the constant offset with arr.useconstantoffset = True and set arr.constantoffsetdisplace[1] = 2.0. Setting the Y element of the displacement vector gives the 2-unit gap along Y.