Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

when does python delete variables?

I know that python has an automatic garbage collector and so it should automatically delete variables when there are no more reference to them.

My impression is that this does not happen for local variables (inside a function).

def funz(z):
    x = f(z) # x is a np.array and contains a lot of data
    x0 = x[0]
    y = f(z + 1) # y is a np.array and contains a lot of data
    y0 = y[0]

    # is x and y still available here?
    return y0, x0

Is del x the right way to save memory?

def funz(z):
    x = f(z) # x is a np.array and contains a lot of data
    x0 = x[0]
    del x
    y = f(z + 1) # y is a np.array and contains a lot of data
    y0 = y[0]
    del y

    return y0, x0

EDIT: I have edited my example such that it is more similar to my real problem. In my real problem x and y are not lists but classes that contain different large np.array.

EDIT: I am able to run the code:

x = f(z)
x0 = x[0]
print(x0)

y = f(z + 1)
y0 = [0]
print(y0)
like image 715
Donbeo Avatar asked Aug 13 '14 12:08

Donbeo


1 Answers

Implementations use reference counting to determine when a variable should be deleted.

After the variable goes out of scope (as in your example) if there are no remaining references to it, then the memory will be freed.

def a():
    x = 5 # x is within scope while the function is being executed
    print x

a()
# x is now out of scope, has no references and can now be deleted

Aside from dictionary keys and elements in lists, there's usually very little reason to manually delete variables in Python.

Though, as said in the answers to this question, using del can be useful to show intent.

like image 166
flau Avatar answered Oct 13 '22 13:10

flau