Active object set, object mode set, but still "RuntimeError: Error: Modifiers cannot be applied in edit mode"?
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')
bpy.ops.object.modifier_add(type='SUBSURF')
bpy.ops.object.modifier_apply(modifier='Subsurf', apply_as='DATA')


Could someone confirm if this is a bug in Blender? Two reasons:


I don't see why other objects are required to be also in object mode for us to apply modifiers to the object of interest.
GUI behavior doesn't match commandline behaviors.