Niccolò
Niccolò

Reputation: 3092

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?

Upvotes: 11

Views: 6324

Answers (3)

Joran Beasley
Joran Beasley

Reputation: 113988

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

Upvotes: 5

jaysoncopes
jaysoncopes

Reputation: 854

So far, in my experience with Python, I haven't had any problems with garbage collection. However, I do take precautions, not only because I don't want to bother with any unreferenced objects, but also for organization reasons as well.

To answer your questions specifically:

1) Yes, I would recommend deleting the object. This will keep your code from getting bulky and/or slow. This is an especially good decision if you have a long run-time for your code, even though Python is pretty good about garbage collection.

2) Either way works fine, although I would use del just for the sake of removing the actual reference itself.

3) I don't know how it "influences the garbage collector" but it's always better to be safe than sorry.

Upvotes: 1

Andrew Gorcester
Andrew Gorcester

Reputation: 19973

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.

Upvotes: 9

Related Questions