Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I delete large object when finished to use them in python?

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?

like image 578
Niccolò Avatar asked Jul 24 '14 16:07

Niccolò


2 Answers

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.

like image 196
Andrew Gorcester Avatar answered Sep 28 '22 07:09

Andrew Gorcester


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

like image 28
Joran Beasley Avatar answered Sep 28 '22 08:09

Joran Beasley