I noticed that when it comes to addons, unregister() gets called both when disabling the addon AND when exiting blender.

I have an operation I only want to perform if the addon is disabled from the user Preferences, but NOT every single time blender closes.

Does anyone know of a way to differentiate between the two situations?

Some context: my addon needs to copy custom matcap files to blender's user path (datafiles/studiolights). The problem is deleting them only when the addon gets unchecked in the preferences, but not every time blender exits. Copying those files into that user path seems to be the only way to install a matcap.

  • $\begingroup$ Tentative answer: You could test isinstance(bpy.context.space_data, bpy.types.SpacePreferences) in unregister. If True the addon was likely disabled by the user in the prefs and you could erase the matcaps. False does not necessarily mean Blender is closing though. Not sure how robust this would be; if possible I'd think about an explicit "Uninstall Matcaps" operator. $\endgroup$
    – scurest
    Commented Jan 16, 2021 at 19:04
  • $\begingroup$ Your solution seems to work. My main focus is executing cleanup ONLY when the addon is disabled through preferences; not too concerned about the Blender is Closing scenario. Considering it's just matcaps, I doubt anything can break catastrophically even if this cleanup gets falsely triggered by something else. I just wanted to avoid a dedicated cleanup button for users to press and keep things under the hood. I'll leave the bounty open for a few more days to make the most out of it (I don't have that many points), but I'm happy enough to up-vote you as an answer if no one else drops in. $\endgroup$ Commented Jan 16, 2021 at 20:01

1 Answer 1


Not sure this is the best answer, but you can check if the current space is the Preferences windows in unregister

def unregister():
    if isinstance(bpy.context.space_data, bpy.types.SpacePreferences):
        # your code here

This should run the code when the user disables the addon from the prefs windows and it should not run the code when Blender is closed. In other cases it may or may not run, so this only works if "best effort disable-detection" is okay for you (it sounds like it is).


You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .