0

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.

Wojtas.Zet
  • 636
  • 2
  • 10
  • 30
  • I processed some bigger data sets (like > 20 TB on regular bases). It was OCR, image processing, natural language processing thing. I never bothered deleting anything explicitly. Just do not point to the value once you do not need it. Once nothing is pointing to that object it should be removed and usually it works very well. https://rushter.com/blog/python-garbage-collector/#:~:text=Reference%20counting%20is%20a%20simple,to%20the%20right%2Dhand%20side. – petrch Oct 12 '20 at 14:20

1 Answers1

1

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.

Carcigenicate
  • 43,494
  • 9
  • 68
  • 117