Is there a way to distinguish the manual deletion of an object?

3

It is understood that distinguish it from the deletion made by the garbage collector. I would like the explicit deletion:

del objeto

It will execute something that does not run when the object disappears because the garbage collector detects that it is no longer necessary.

I know I can do something like:

objeto.delete()

to execute the additional code I want, but it does not seem quite elegant, because the object still exists.

My need arises that I am writing a small orm and the object is associated with its corresponding record in the database. I would like that deleting the object explicitly means deleting the record, while letting the die object, have no effect on the database.

    
asked by José Miguel SA 17.01.2016 в 22:42
source

1 answer

6

I think you do not understand well how the deletion of objects works. With del objeto what you do is delete one of the references to the object, but there could be more. The most common, for example, is that you have it referenced from attributes of other objects. A rule to keep in mind is that the object will always be alive as long as there is a living reference to it. And only when the last reference has disappeared, the object will be erased from memory.

Prior to memory clearing, the __del__ method is executed. I do not think it's the best place to erase records from a database.

I'll give you an illustrative example:

class C:
  def __del__(self):
    print("Borrado del objeto")

a = C()
b = a

print("Intento de borrado 1")
del a

print("Intento de borrado 2")
del b

If you test it, you will see that the __del__ method is not invoked until the b reference has disappeared.

That said, notice that it is impossible to force the deletion of all references to an object unless you had created them as weak references ( weakrefs ).

But I do not see how you can avoid creating a specific method in the ORM to erase records.

If you want to dig deeper, some time ago I wrote an article on the life of objects .

    
answered by 18.01.2016 / 01:28
source