3

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?

Zen
  • 4,381
  • 5
  • 29
  • 56

3 Answers3

1

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.

loopbackbee
  • 21,962
  • 10
  • 62
  • 97
1

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)

Constantinius
  • 34,183
  • 8
  • 77
  • 85
1

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
>>>
xmo
  • 203
  • 4
  • 9
  • He wrote a lot of other codes. I think he is going to use self['key'] = value method – Zen May 09 '14 at 13:48