Python - Delete (remove from memory) a variable from inside a function?

25,469

del A will simply remove A from the local scope of function (see this answer). A will still persist in the global scope. To remove it from the global scope you can either use a closure (and declare global A) or with python3 you can also use the keyword nonlocal. However this only removes the binding from the scope and does not guarantee that the corresponding memory is freed. This happens when the object is garbage collected. You can force garbage collection via the gc module (see this answer).

However if you are running into memory problems, instead of loading the whole data set, you could maybe use a view onto the data set and only process (load) a part of it at a time (i.e. stream-process the data).

Share:
25,469
Dominique Makowski
Author by

Dominique Makowski

Neuropsychologist by day & coder by night. Actually by day too. https://dominiquemakowski.github.io/

Updated on July 26, 2020

Comments

  • Dominique Makowski
    Dominique Makowski almost 4 years

    I have to load this massive object A (that can weight almsot 10go) that I need to pass to a function, that extracts from it a parameter B to further exert some heavy computations on it.

    A = load(file)
    
    def function(A):    
       B = transorm(A)    
       B = compute(B)
       return(B)
    

    In order to free some memory (as I already had a MemoryError), I'd like to remove A from memory right after its transformation to B. I tried del but it doesn't seem to affect the existence of A at the script level. I also tried del global()["A"] but it says that A is not defined as a global variable.

    Is there a way to do it? Thanks!

  • Totem
    Totem over 7 years
    Setting A = None inside the function will not change the value of A outside the function after it has returned. A = None there only sets a value for A in the local scope.
  • Samuel Muldoon
    Samuel Muldoon over 3 years
    Imagine people that you are at a large business convention or meeting. There are many people wearing write-on name-tags/stickers on their shirts. There are many people at this business function, including a Ms. Sarah, and "Mr. None". Initially, Sarah is wearing a name-tag on her shirt on which says "A". Executing the code A = None is like (1) taking the "A" name-tag off Ms. Sarah (2) sticking the "A" name-tag onto Mr. None. Executing the code A = None does not remove Sarah from the convention. Before, Sarah's name-tag said, "A."
  • Samuel Muldoon
    Samuel Muldoon over 3 years
    Afterwards, Sarah has no name-tag at all, the A name-tag is moved to Mr. None's shirt .