How to modify a key and register another key at the same time in an addon?

If you want to edit existing keymap items, you should use wm.keyconfigs.active. This ensures that your addon can override the currently active keymap in Blender.

You should also disable a keymap item (and add your own via wm.keyconfigs.addon) instead of modifying it.

wm.keyconfigs.user is a bit hard to work with. I recommend to avoid using it to add or modify keymaps.

This example searches for a specific keymap based on traits like its identifier, type, value, and modifier keys. If a keymap is found based on the criteria, it gets disabled and added to a list (so you can re-enable the keymap item when the addon is unregistered).

import bpy

disabled_kmis = []

# Find a keymap item by traits.
# Returns None if the keymap item doesn't exist.
def get_active_kmi(space: str, **kwargs) -> bpy.types.KeyMapItem:
    kc = bpy.context.window_manager.keyconfigs.active
    km = kc.keymaps.get(space)
    if km:
        for kmi in km.keymap_items:
            for key, val in kwargs.items():
                if getattr(kmi, key) != val and val is not None:
                    break
            else:
                return kmi

def disable_shift_s_snap_kmi():
    # Be explicit with modifiers shift/ctrl/alt so we don't
    # accidentally disable a different keymap with same traits.
    kmi = get_active_kmi("3D View",
                         idname="wm.call_menu_pie",
                         type='S',
                         shift=True,
                         ctrl=False,
                         alt=False)

    if kmi is not None:
        kmi.active = False
        disabled_kmis.append(kmi)

if __name__ == "__main__":
    disable_shift_s_snap_kmi()
    
    # Register your own version of Shift S with click drag
    # just like you would with any addon hotkey.
    ...
    

To re-enable the disabled keymap items when the addon is uninstalled:

def register():
    for kmi in disabled_kmis:
        kmi.active = True
    
    ...
1 Like