# Confused with how to stack bpy calls

I am calling a script with this command and it fails.

class QuickOrigin(bpy.types.Operator):
bl_idname = "quick.origin"
bl_label = "Set Origin"
bl_options = {'REGISTER'}

def execute(self, context):
if bpy.context.mode != 'EDIT_MESH':
bpy.ops.object.editmode_toggle()
return{'FINISHED'}

bpy.ops.view3d.snap_cursor_to_selected()
bpy.ops.object.editmode_toggle()
bpy.ops.object.origin_set(type='ORIGIN_CURSOR')
bpy.ops.object.editmode_toggle()
return{'FINISHED'}


The problem is the "bpy.ops.object.editmode_toggle()" command after "bpy.ops.object.origin_set(type='ORIGIN_CURSOR')"

Why cannot I just add "bpy.ops.object.editmode_toggle()" in a new line.

But when I do it this way it works.

class QuickOrigin(bpy.types.Operator):
bl_idname = "quick.origin"
bl_label = "Set Origin"
bl_options = {'REGISTER'}

def execute(self, context):
if bpy.context.mode != 'EDIT_MESH':
bpy.ops.object.editmode_toggle()
return{'FINISHED'}

bpy.ops.view3d.snap_cursor_to_selected()
bpy.ops.object.editmode_toggle()
bpy.ops.object.origin_set(type='ORIGIN_CURSOR')

if bpy.context.mode != 'Object':
bpy.ops.object.editmode_toggle()
return{'FINISHED'}
return{'FINISHED'}


You can avoid the ambiguity of the situation by explicitly setting the object's mode to what you want in each stage:

class QuickOrigin(bpy.types.Operator):
bl_idname = "quick.origin"
bl_label = "Set Origin"
bl_options = {'REGISTER'}

def execute(self, context):
if context.object.mode == 'OBJECT':
bpy.ops.object.mode_set( mode = 'EDIT' )
return{'FINISHED'}

bpy.ops.view3d.snap_cursor_to_selected()
bpy.ops.object.mode_set( mode = 'OBJECT' )
bpy.ops.object.origin_set(type='ORIGIN_CURSOR')
bpy.ops.object.mode_set( mode = 'EDIT' )
return{'FINISHED'}

• Can you give me a reasonable n why my attempt does not work? I don't see the logic behind the error. – Claas Kuhnen Jan 6 '16 at 3:16
• I think its probably the use of mode toggle. You don't really have control over which mode the object is in and can find yourself in the wrong mode for some operators (origin_set works only in object mode for instance). So explicit mode setting is a safer approach here. – TLousky Jan 6 '16 at 7:20