Catch those keymaps

Are you an addon devel­op­er? I have some­thing to show you.

You may know Blender has a -b para­me­ter that lets it run with­out a GUI. This can be used to ren­der on servers, or in batch­es (like Render+ does).

What you may not know is that when Blender runs GUI-less the addons key­con­figs aren’t avail­able and try­ing to access the keymaps rais­es an AttributeError.

Exception in module register(): '/home/januz/.config/blender/2.79/scripts/addons/XXXX.py'
Traceback (most recent call last):
File "/home/januz/code/blender_RC/bin/2.79/scripts/modules/XXXX.py", line 350, in enable
mod.register()
File "/home/januz/.config/blender/2.79/scripts/addons/XXXX.py", line 1009, in register
km = wm.keyconfigs.addon.keymaps.new(name='Object Mode', space_type='EMPTY')
AttributeError: 'NoneType' object has no attribute 'keymaps'

I have about five addons enabled now that spit this error. It’s harm­less and doesn’t affect the ren­der at all but it does fill the screen (and logs) very quick­ly mak­ing it hard­er to find impor­tant errors. Or maybe it just trig­gers my OCD 🙂

So if you are an addon writer, con­sid­er putting keymaps in a try block to catch that exception.

try:
    wm = bpy.context.window_manager
    km = wm.keyconfigs.addon.keymaps.new(name='Object Mode', space_type='EMPTY')

except AttributeError as e:
    if bpy.app.background:
        # Silence is golden
        pass
    else:
        # Not running in the background, something actually went wrong.
        # Re-raise the exception
        raise e
All the posts you can read
ArticlesBlender, Python21.10.2020