I have been using python for a while now and Im happy using it in most forms but I am wondering which form is more pythonic. Is it right to emulate objects and types or is it better to subclass or inherit from these types. I can see advantages for both and also the disadvantages. Whats the correct method to be doing this?
Subclassing method
class UniqueDict(dict):
def __init__(self, *args, **kwargs):
dict.__init__(self, *args, **kwargs)
def __setitem__(self, key, value):
if key not in self:
dict.__setitem__(self, key, value)
else:
raise KeyError("Key already exists")
Emulating method
class UniqueDict(object):
def __init__(self, *args, **kwargs):
self.di = dict(*args, **kwargs)
def __setitem__(self, key, value):
if key not in self.di:
self.di[key] = value
else:
raise KeyError("Key already exists")
Key question you have to ask yourself here is:
Imagine new methods are added to
dictwhich you don’t override in yourUniqueDict. If you want to express thatUniqueDictis simply a small derivation in behaviour fromdict‘s behaviour, then you’d go with inheritance since you will get changes to the base class automatically. If you want to express thatUniqueDictkinda looks like adictbut actually isn’t, you should go with the ’emulation’ mode.