3

The other day I came across this snippet of code online and it made me wonder about managing memory in Python (something I've never actively done when writing scripts in Python).

# delete the uneeded df
del new_train
del old_train
del val_df
gc.collect()

As far as I can tell, the code deletes the references to three variables and then explicitly calls Python's GC to release unreferenced memory as outlined by this SO post.

My question is, should I be actively doing this in my Python scripts to keep my memory footprint low and are there any downsides to doing this? Are there any other memory management steps like this that I should incorporate into my Python scripts?

ptk
  • 6,835
  • 14
  • 45
  • 91
  • 3
    No, it is not. The accepted answer in that linked duplicate is highly misleading. Indeed, `gc` only even handles the cyclic garbage collector, CPython uses reference counting as it's memory management scheme, and objects are reclaimed *immediately* when their reference count reaches zero. It is good practice to write well organized code that doesn't just leave a bunch of objects in the global namespace, preventing them from being garbage collected. – juanpa.arrivillaga Jul 21 '19 at 03:45

0 Answers0