Subclassing dict: should dict.__init__() be called? Subclassing dict: should dict.__init__() be called? python python

Subclassing dict: should dict.__init__() be called?


You should probably call dict.__init__(self) when subclassing; in fact, you don't know what's happening precisely in dict (since it's a builtin), and that might vary across versions and implementations. Not calling it may result in improper behaviour, since you can't know where dict is holding its internal data structures.

By the way, you didn't tell us what you want to do; if you want a class with dict (mapping) behaviour, and you don't really need a dict (e.g. there's no code doing isinstance(x, dict) anywhere in your software, as it should be), you're probably better off at using UserDict.UserDict or UserDict.DictMixin if you're on python <= 2.5, or collections.MutableMapping if you're on python >= 2.6 . Those will provide your class with an excellent dict behaviour.

EDIT: I read in another comment that you're not overriding any of dict's method! Then there's no point in subclassing at all, don't do it.

def createImageDb(directory):    d = {}    # do something to fill in the dict    return d

EDIT 2: you want to inherit from dict to add new methods, but you don't need to override any. Than a good choice might be:

class MyContainer(dict):    def newmethod1(self, args):        pass    def newmethod2(self, args2):        passdef createImageDb(directory):    d = MyContainer()    # fill the container    return d

By the way: what methods are you adding? Are you sure you're creating a good abstraction? Maybe you'd better use a class which defines the methods you need and use a "normal" dict internally to it.

Factory func:http://en.wikipedia.org/wiki/Factory_method_pattern

It's simply a way of delegating the construction of an instance to a function instead of overriding/changing its constructors.


You should generally call base class' __init__ so why make an exception here?

Either do not override __init__ or if you need to override __init__ call base class __init__, If you worry about arguments just pass *args, **kwargs or nothing if you want empty dict e.g.

class MyDict(dict):    def __init__(self, *args, **kwargs ):        myparam = kwargs.pop('myparam', '')        dict.__init__(self, *args, **kwargs )

We shouldn't assume what baseclass is doing or not doing, it is wrong not to call base class __init__


Beware of pickling when subclassing dict; this for example needs __getnewargs__ in 2.7,and maybe __getstate__ __setstate__ in older versions. (I have no idea why.)

class Dotdict( dict ):    """ d.key == d["key"] """    def __init__(self, *args, **kwargs):        dict.__init__( self, *args, **kwargs )        self.__dict__ = self    def __getnewargs__(self):  # for cPickle.dump( d, file, protocol=-1)        return tuple(self)