Search code examples
pythonpython-datamodel

Python std methods hierarchy calls documented?


just encountered a problem at dict "type" subclassing. I did override __iter__ method and expected it will affect other methods like iterkeys, keys etc. because I believed they call __iter__ method to get values but it seems they are implemented independently and I have to override all of them.

Is this a bug or intention they don't make use of other methods and retrieves values separately ?

I didn't find in the standard Python documentation description of calls dependency between methods of standard classes. It would be handy for sublassing work and for orientation what methods is required to override for proper behaviour. Is there some supplemental documentation about python base types/classes internals ?


Solution

  • Subclass Mapping or MuteableMapping from the collections module instead of dict and you get all those methods for free.

    Here is a example of a minimal mapping and some of the methods you get for free:

    import collections
    class MinimalMapping(collections.Mapping):
        def __init__(self, *items ):
            self.elements = dict(items)
        def __getitem__(self, key):
            return self.elements[key]
        def __len__(self):
            return len(self.elements)
        def __iter__(self):
            return iter(self.elements)
    
    t = MinimalMapping()
    print (t.iteritems, t.keys, t.itervalues, t.get)
    

    To subclass any of the builtin containers you should always use the appropriate baseclass from the collections module.