Bind a Function to Delete Object

Hey there,
is it possible to bind a function to an object that is being executed, when the object is being deleted?

I managed to somehow do it, with a depsgraph_update_post handler, but this only works, when a single object is being deleted.
What I would like to have, is a specific function that is executed on every object that is being deleted indivually.

You can run a function when an object is removed with __del__ but AFAIK this happens after the data block is invalidated so running self.name or equivalent will throw an error. So the usefulness will be somewhat limited. Depends on your end goal.

import bpy

def del_obj(self):
    print("I was deleted") # OK
    print(f"{self.name} was deleted")  # ReferenceError
bpy.types.Object.__del__ = del_obj
1 Like

Does this overwrite anything existing and will conflict with other addons?

It sure is extremely hacky and wouldn’t recommend in a production tool. AFAIK __del__ is not explicitely defined in the python API so you can override it. Subject to change in the future though, we never know. However you can’t prevent name collision with other addons. Again no reliable addon would be released with such a hack anyway :wink:

Maybe something like that :

More seriously you should do something like that. this will not scale well if you have thousands of objects.

import bpy

uids = set()
id_object_map = {}


def my_handler(scene):
    global uids
    global id_object_map
    objects_ids = set([o.session_uid for o in bpy.data.objects])
    id_object_map.update({o.session_uid: o.name for o in bpy.data.objects})
    difference = uids - objects_ids
    
    for uid in difference:
        print(f"{id_object_map[uid]} was deleted")
    
    uids = objects_ids


bpy.app.handlers.depsgraph_update_post.append(my_handler)