# Active object set, object mode set, but still "RuntimeError: Error: Modifiers cannot be applied in edit mode"?

I'm trying to apply my modifier to object with Python. I've set the object of interest as the active object and ensured its mode to be object. However, I still receive this error.

Here's the relevant code.

bpy.context.scene.objects.active = obj
bpy.ops.object.mode_set(mode='OBJECT')
bpy.ops.object.modifier_apply(modifier='Subsurf', apply_as='DATA')

RuntimeError: Error: Modifiers cannot be applied in edit mode


I saved the .blend file right before the error and opened this file in GUI. Then, I ran

bpy.ops.object.modifier_apply(modifier='Subsurf', apply_as='DATA')


that used to cause errors in the command pane, and weirdly it ran without errors!

I checked the object of interest, obj, is indeed in object mode, but there was one object, which was neither active nor selected, in edit mode. When I made all objects be in object mode, the error was gone.

for o in bpy.data.objects:
bpy.context.scene.objects.active = o
bpy.ops.object.mode_set(mode='OBJECT')
o.select = False
obj.select = True
bpy.context.scene.objects.active = obj

bpy.ops.object.mode_set(mode='OBJECT')