One simple way is to add an if-statement to the body of the handler in order to determine whether the rest of the code should execute by using one additional Bool or EnumProperty declared in the preferences of your add-on:
class MYTOOL_AP_preferences(bpy.types.AddonPreferences):
...
state: bpy.props.BoolProperty(name="Switch")
...
def my_save_handler(dummy):
if state:
...
Demo on how the user can disable the handler via Preferences using one EnumProperty:
import bpy
bl_info = {"name": "Stats Add-on", "blender": (2, 82, 0), "category": "System"}
class MYTOOL_AP_preferences(bpy.types.AddonPreferences):
# this must match the add-on name, use 'package'
# when defining this in a submodule of a python package.
bl_idname = name
state: bpy.props.EnumProperty(name="Switch", default = 'ON',
items=(("ON", "On", "", 1), ("OFF", "Off", "", 2)))
def draw(self, context):
self.layout.row().prop(self, "state", expand=True)
def my_save_handler(dummy):
if bpy.context.preferences.addons[name].preferences.state == 'ON':
print ("Blend file has been saved.")
def register():
bpy.utils.register_class(MYTOOL_AP_preferences)
bpy.app.handlers.save_post.append(my_save_handler)
def unregister():
bpy.app.handlers.save_post.remove(my_save_handler)
bpy.utils.unregister_class(MYTOOL_AP_preferences)
if name == "main":
register()
BATHandlersclass to handle this very thing among others. – batFINGER Sep 17 '21 at 08:57context.scenerather thanselfwill not always work as expected when there are more than one scene. Speaking of comments, tempted to "Maybe they downvoted by mistake @drf speaking of tools, can the mods see deleted comments?" on that OTT whingey whiney why are my perfect answers downvoted meta post. – batFINGER Oct 12 '21 at 07:27