'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 &lt;module&gt;
  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?
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.