How would I know through a script when the switch to edit mode happens? I need it for modal operator.

I was thinking on listening for 'TAB' event and checking obj.mode, but I hope there is a better way, for reasons like changed edit-mode shortcut or switching to edit-mode by script.


In your modal operator you can test object.mode for which mode the object is in - example:

import bpy

bpy.context.active_object.mode   # = 'OBJECT'


bpy.context.active_object.mode   # = 'EDIT'

There is no callback, you will need to test this on 'tab' event or always to be sure..

  • $\begingroup$ Alternatively, you can check bpy.context.mode which will be EDIT_MESH if in edit mode $\endgroup$ – Justin May 17 '20 at 20:43

There is no way to "trigger" your script when the user enters edit mode. The only way for you to run your own code on entering edit mode is to set the keyboard shortcuts to run your script instead of changing to edit mode.

As it sounds like you are referring to switching to edit mode while your modal operator is running, you will need to check the event and enter edit mode when the tab key is pressed, other operators will not be run while your modal operator is running.

def modal(self, context, event):
    if event.type == 'TAB':
        if context.active_object.mode == 'EDIT':
            bpy.ops.object.mode_set(mode='OBJECT', toggle=False)
            bpy.ops.object.mode_set(mode='EDIT', toggle=False)
  • 2
    $\begingroup$ other operators will be run if the modal returns {'PASS_THROUGH'} $\endgroup$ – Jaroslav Jerryno Novotny Dec 26 '14 at 20:14

In 2.8, you can use message bus to do that:

The principle is to obtain the path using a path name through the object.

Then declare a subscription to message bus.

import bpy

#The callback when then change occurs
def a_callback(object, data):
    print( object, data, "changed" )

def subscribe_to(object,data_path,callback):

    #Get a rna subscription link from the object
    subscribe_to = object.path_resolve(data_path, False)

    #Effectively subscribe to the rna path from the object

subscribe_to(bpy.context.object,"mode", a_callback)

Note: bpy.msgbus is not documented for now. But it contains few functions that we can find using the Python console:

enter image description here

  • $\begingroup$ Or via context.mode? $\endgroup$ – batFINGER Mar 10 '20 at 11:36
  • $\begingroup$ @batFINGER, is it supported? $\endgroup$ – lemon Mar 10 '20 at 11:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.