Wojtas.Zet
Wojtas.Zet

Reputation: 816

Destroying python object after removing it from list of objects

I have an object:

class Flow:

this object belongs to list of objects flowList = [Flow1, Flow2, Flow3]

If I do:

del flowList[0]

Do I need to destroy as well Flow1 object? I want my script to process thousands of flows and be memory efficient. Processed flow should die after processing as it won't be needed anymore.

Upvotes: 0

Views: 46

Answers (1)

Carcigenicate
Carcigenicate

Reputation: 45745

No, this is not required, and there are no reliable ways that I know of of explicitly freeing certain memory anyways.

Python uses Garbage Collection, which means it automatically disposes of objects when they are no longer needed. Once you're done with an object, you can simply leave it. If the only reference to Flow1 was the one inside the list, del flowList[0] is sufficient to allow it to be freed. If there's another reference outside of the list, you can do del Other_Flow1 to delete the other reference to allow it to be freed.


If you have something like this:

huge_list = [1, 2, 3, . . .]
use_huge_list(huge_list)

You could add something like this after the call to use_huge_list to help free huge_list more readily:

del huge_list

This deletes the reference huge_list to the [1, 2, 3, . . .] object. If that's the only reference to the object, it will allow it to be freed. I'd only do this though if memory is a huge concern, and huge_list will remain in scope for an extended period of time, but is never used (although, that may be a smell that suggests that you need to refactor anyway).


I would not use del like that constantly though. It's unnecessary to delete labels in 99% of cases. Don't overthink it. Unless you've profiled and know for sure that objects staying in memory are causing you problems, don't worry about it.

Upvotes: 1

Related Questions