ZengJuchen
ZengJuchen

Reputation: 4811

what's the usage of inherit 'dict' with a class?

I saw one of my colleague write his code like:

class a(dict):
    # something
    pass

Is this a common skill? What does it serve for?

Upvotes: 3

Views: 222

Answers (3)

xmo
xmo

Reputation: 213

Extending the built-in dict class can be useful to create dict "supersets" (e.g. "bunch" class where keys can be accessed object-style, as in javascript) without having to reimplement MutableMapping's 5 methods by hand.

But if your colleague literally writes

class MyDict(dict):
    pass

without any customisation, I can only see evil uses for it, such as adding attributes to the dict:

>>> a = {}
>>> a.foo = 3
AttributeError: 'dict' object has no attribute 'foo'
>>> b = MyDict()
>>> b.foo = 3
>>>

Upvotes: 1

Constantinius
Constantinius

Reputation: 35039

In some cases it makes sense. For example you could create a dict that allows case insensitive lookup:

class case_insensitive_dict(dict):
    def __getitem__(self, key):
        return super(case_insensitive_dict, self).__getitem__(key.lower())

    def __setitem__(self, key, value):
        return super(case_insensitive_dict, self).__setitem__(key.lower(), value)


d = case_insensitive_dict()
d["AbCd"] = 1
print d["abcd"]

(this might require additional error handling)

Upvotes: 1

loopbackbee
loopbackbee

Reputation: 23322

This can be done when you want a class with the default behaviour of a dictionary (getting and setting keys), but the instances are going to be used in highlu specific circumstances, and you anticipate the need to provide custom methods or constructors specific to those.

For example, you may want have a dynamic KeyStorage that starts as a in-memory store, but later adapt the class to keep the data on disk.

You can also mangle the keys and values as needed - for storage of unicode data on a database with a specific encoding, for example.

Upvotes: 1

Related Questions