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

后端 未结 7 1577
梦毁少年i
梦毁少年i 2020-12-23 17:26

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 delet

7条回答
  •  -上瘾入骨i
    2020-12-23 17:42

    Have you even tried running the code? The following code with Python 3.7 throws exception! "RuntimeError: dictionary changed size during iteration":

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

    All previous answers are good. I just wanted to add couple more points about the differences of del and clear:

    1. my_dict.clear(); removes all the items in the dictionary and makes it equivalent to empty dictionary. Note: you still can add items to it if you want!
    2. del my_dict; makes the object of my_dict to be deleted and garbage collection eligible (my_dict is not usable anymore)! So, if you try to add/access any item then you will get an exceptions.
    3. Also, you have declared two variables my_obj_1 and my_obj_2; Even if you delete/clear my_dict, those two variables are holding references to MyClass objects and won't be going away until my_obj_1 and my_obj_2 are out of scope; so, if MyClass objects hold memory (say list or something) then if your intention is to release the memory by deleting/clearing my_dict, it is not happening!

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

      my_obj_1 = MyClass() my_obj_2 = MyClass()

提交回复
热议问题