# Applying modifiers in a script

I've seen a couple of good examples of creating modifiers and applying them to objects, but they don't seem to be working for me. Or at least are only working part way.

My function takes a modifier type (in my test case, 'UNION') and a list of objects. The first object is the target and the rest are going to be the modifications.

When this executes, my target still has the stack of modifiers attached to it. I have to manually push the Apply button in the UI for each one. How can I make that happen in my script?

def applyModifier (self, mod, items):
target = items[0]
for i in range(1, len(items)):
objB = items[i]
boo = target.modifiers.new('Booh', 'BOOLEAN')
boo.object = objB
boo.operation = mod
bpy.ops.object.modifier_apply(apply_as='DATA', modifier="Booh")
return target


The subordinate objects do unlink from the scene, so I know that bit of code is executing properly.

• Have a look at Object.to_mesh(): blender.org/documentation/blender_python_api_2_71_release/… If you want to apply all modifiers, then it's probably the better way. Nonetheless, bpy.ops can be the better (or only) choice in certain use cases. – CodeManX Sep 5 '14 at 18:49
• That one looks interesting, too. I'll give it a shot. One of the frustrations with Blender seems to be that there are multiple ways of accomplishing things, but the advantages and disadvantages aren't always clear. – artk2002 Sep 6 '14 at 3:44

Since you're using something from bpy.ops, you need to get the editor state right (this is the failing of most of bpy.ops).
You probably need to set bpy.context.scene.objects.active = target
context.view_layer.objects.active = target