# 'Context is incorrect' error when using 'bpy.ops.object.mode_set(mode='OBJECT')' if I'm already in object mode

I'm trying to do things that only work in object mode. This gives me three choices:

• I can hope I'm in object mode, and my script will raise an error if I'm not.

• I can hope I'm in pose mode (or some other specific mode) and use bpy.ops.object.posemode_toggle() to switch out of it.

• I can hope I'm not in object mode, run bpy.ops.object.mode_set(mode='OBJECT') to switch into it, and my program will raise an error if I'm already in it.

If I go with that last option I'm getting the error message

Traceback (most recent call last):
File "C:\Users\daniel\Desktop\BlenderMusic\keyboard.blend\fingers", line 5, in <module>
File "C:\Program Files\WindowsApps\BlenderFoundation.Blender_2.82.1.0_x64__ppwjx1n5r4v9t\Blender 2.82\2.82\scripts\modules\bpy\ops.py", line 201, in __call__
ret = op_call(self.idname_py(), None, kw)
RuntimeError: Operator bpy.ops.object.mode_set.poll() failed, context is incorrect


There's nothing I can do to just let my script run no matter what mode it's in without crashing. Am I missing something?

Also, why is posemode_toggle() even a thing? How can you be in a situation where you don't know whether or not you're in pose mode, but if you're in it you need to not be in it and if you're not in it you need to be in it?

• Hi. Aa you used the word 'crashing' do you mean blender is closing as a result of running this? – Ray Mairlot May 22 '20 at 11:39
• I just mean it's raising an exception. – DanielLC May 23 '20 at 5:23

You can check which mode you're in with the following line:

mode = context.active_object.mode


And then do things correspondingly, such as switching to object mode when you're in pose mode for example.

Or you could use a try/except statement:

try:
bpy.ops.object.mode_set(mode='OBJECT')
except:
pass


Hope this helps.

Making that happen?

Given of-course there is a scene, the only way I'm aware of to have set mode operator fail is to have no active object. Calling op to object mode from object mode is not an issue.

Is it possible that in your code this can happen? Are you running from a timer thread? Recommend editing a script example inTO question showing giving more context.

Python console test

>>> C.mode
'OBJECT'

>>> C.object
bpy.data.objects['Cube']

>>> bpy.ops.object.mode_set.poll()
True

>>> bpy.ops.object.mode_set()
{'FINISHED'}

>>> bpy.ops.object.mode_set(mode='OBJECT')
{'FINISHED'}

>>> C.view_layer.objects.active = None
>>> bpy.ops.object.mode_set.poll()
False

>>> bpy.ops.object.mode_set()
Traceback (most recent call last):
File "<blender_console>", line 1, in <module>
File "../modules/bpy/ops.py", line 201, in __call__
ret = op_call(self.idname_py(), None, kw)
RuntimeError: Operator bpy.ops.object.mode_set.poll() failed, context is incorrect