Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

python - Does dictionary's clear() method delete all the item related objects from memory?

If a dictionary contains mutable objects or objects of custom classes (say a queryset, or a even a DateTime), then will calling clear() on the dictionary delete these objects from memory? Does it behave differently than looping through the dict and deleting them?

eg. consider

class MyClass(object):
    '''Test Class.'''

my_obj_1 = MyClass()
my_obj_2 = MyClass()

my_dict = { 'foo' : my_obj_1, 'bar' : my_obj_2 }

then is

my_dict.clear()

same as

for key in my_dict.keys():
    del my_dict[key]

?

question from:https://stackoverflow.com/questions/10446839/does-dictionarys-clear-method-delete-all-the-item-related-objects-from-memory

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

1 Answer

0 votes
by (71.8m points)

Python documentation on dicts states that del d[key] removes d[key] from the dictionary while d.clear() removes every key, so basically their behavior is the same.

On the memory issue, in Python when you "delete" you are basically removing a reference to an object. When an object is not referenced by any variable nor other object or becomes unreachable, it becomes garbage and can be removed from memory. Python has a garbage collector that from time to time it does this job of checking which objects are garbage and releases the memory allocated for them. If the object you are deleting from the dictionary is referenced by other variable then it is still reachable, thus it is not garbage so it won't be deleted. I leave you here some links if you are interested in reading about garbage collection in general and python's garbage collection in particular.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...