Donbeo - 5 months ago 42

Python Question

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 still available here ?

return y[0], x[0]

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]

return y[0], x[0]

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 list but class that contains different long np.array

EDIT: I am able to run the code:

`x = f(z)`

x[0]

print(x0)

y = f(z + 1)

y0 = [0]

print( y0)

Answer

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.