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.

1
  • 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. rushter.com/blog/python-garbage-collector/…. Commented Oct 12, 2020 at 14:20

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.