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
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:
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()