# Know when edit-mode is entered by script? (python)

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.ops.object.mode_set(mode='EDIT')

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


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

• Alternatively, you can check bpy.context.mode which will be EDIT_MESH if in edit mode May 17, 2020 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)
else:
bpy.ops.object.mode_set(mode='EDIT', toggle=False)

• other operators will be run if the modal returns {'PASS_THROUGH'} Dec 26, 2014 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
bpy.msgbus.subscribe_rna(
key=subscribe_to,
owner=object,
args=(object,data_path,),
notify=callback,
)

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:

• Or via context.mode? Mar 10, 2020 at 11:36
• @batFINGER, is it supported? Mar 10, 2020 at 11:46