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

后端 未结 7 1609
梦毁少年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条回答
  •  悲哀的现实
    2020-12-23 17:31

    Does it behave differently than looping through the dict and deleting them?

    It's worth noting here that any custom class implementing the MutableMapping abstract base class gets clear() as a "free" mixin method.

    The only methods you need to override in order to instantiate a MutableMapping subclass are:

    __getitem__, __setitem__, __delitem__, __iter__, __len__
    

    Since you can store the data in your mapping class any way you like, the only way clear() can figure out how to actually clear your data is by using one or more of those five methods. Now, you might have a guess as to which methods clear() is using, but why guess when we can experiment?

    import collections
    
    class MyMap(collections.MutableMapping):
        def __init__(self, mydict):
            self._top_secret_data = mydict
    
        def __getitem__(self, key):
            print 'getitem'
            return self._top_secret_data[key]
    
        def __setitem__(self, key, value):
            raise Exception('where did you want that?')
    
        def __len__(self):
            raise Exception('a gentleman never tells')
    
        def __delitem__(self, key):
            print '[shredding intensifies]'
            del self._top_secret_data[key]
    
        def __iter__(self):
            def keygen():
                for key in self._top_secret_data:
                    print 'faster! faster!'
                    yield key
            return iter(keygen())
    

    Using the class defined above, it's easy to see how clear() is implemented:

    >>> m = MyMap({1:'a', 2:'b', 3:'c'})
    >>> m.clear()
    faster! faster!
    getitem
    [shredding intensifies]
    faster! faster!
    getitem
    [shredding intensifies]
    faster! faster!
    getitem
    [shredding intensifies]
    >>> 
    

    In other words, the clear() mixin method is basically implemented as for key in self: del self[key].

    Now, a disclaimer: Built-in types such as dict are implemented in C, so the dict.clear method may not be literally identical to for key in mydict: del mydict[key]. I would expect some optimization behind the scenes, perhaps a completely different strategy - but hopefully this example gives you some idea as to how you might expect a clear() method to work in Python.

提交回复
热议问题