Using __del__ as object remove callback

Hi folks,

I just found that you could do

bpy.types.Object.__del__ = lambda self: print(f"Bye {self.name}")

Then you get an object remove callback function.

Is this really legal?
Is there any drawback?

If so, is there any proper approach other than comparing scene object names in bpy.app.handlers.depsgraph_update_post?

Thanks :slight_smile:

Ah, that __del__ also gets called on Undo/Redo. :blush:

Nice, good find :slight_smile: Have you tried changing it to “+=” instead of “=”? The only drawback I could see is that you might be overriding the del method, I’m not 100% sure what del does but it’s probably best if it keeps doing it in addition to whatever else :wink:

I say, if it works, use it! I could see this being super useful- for example, if you want to purge unused data blocks upon object deletion to remove any lingering materials/textures/images

Hey @joseph , thanks!

Nah, that doesn’t work. __del__ should be a method so cannot use addition operator on it. :slight_smile:

Anyway, I didn’t use this trick at the end since I only want it to be triggered when the object is really being deleted, not also by Undo/Redo.

Now, I am no expert of Blender but here’s what I think about the reason why Undo/Redo also triggers __del__.

The Python objects that we get from Blender are much like pointers (the address to the data, not the data itself) that points to Blender’s internal datablock. And when some of the data changed, like, after undo, Blender kills the corresponding objects that we kept in hand as they are outdated and may now pointing to void. And when the killing happens, __del__ called by Python’s rule (garbage collecting).



My end solution is using bpy.props.PointerProperty to store the object (bpy.types.Object instances) that I want to track to.

An interesting behavior that I found is when an object is being “captured” by a bpy.props.PointerProperty, the user count increased.

Meaning when pressing X in viewport, object gets deleted from scene but still exists in bpy.data.objects so I can still check on it and do my things.

However! If you press X key above Blender outliner, the object vanished even from bpy.data.objects regardless the user count. And the value of my pointer property turn to None.

But None is fine. I would still know that object is deleted. Just have to pick another place instead of that object to store my custom data since those data is required after the deletion.

Cheers :beers:

1 Like