Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
678 views
in Technique[技术] by (71.8m points)

memory - 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)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...