Assume to not have any particular memory-optimization problem in the script, so my question is about Python coding style. That also means: is it good and common python practice to dereference an object as soon as whenever possible? The scenario is as follows.
Class A
instantiates an object as self.foo
and asks a second class B
to store and share it with other objects.
At a certain point A
decides that self.foo
should not be shared anymore and removes it from B
.
Class A
still has a reference to foo, but we know this object to be useless from now on.
As foo is a relatively big object, would you bother to delete the reference from A and how? (e.g. del
vs setting self.foo = None
) How this decision influence the garbage collector?
If, after deleting the attribute, the concept of accessing the attribute and seeing if it's set or not doesn't even make sense, use del
. If, after deleting the attribute, something in your program may want to check that space and see if anything's there, use = None
.
The garbage collector won't care either way.
del Blah
will reduce the reference count of Blah by one ... once there are no more references python will garbage collect it
self.foo = None
will also reduce the reference count of Blah by one ... once there are no more references python will garbage collect it
neither method actually forces the object to be destroyed ... only one reference to it
*
as a general rule of thumb I would avoid using del
as it destroys the name and can cause other errors in your code if you try and reference it after that ...
in cPython (the "normal" python) this garbage collection happens very regularly
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With