Creating dictionary-like objects in Python using DictMixin


/ Published in: Python
Save to your folder(s)



Copy this code and paste it in your HTML
  1. """How to create a custom mappable container (dictionary-like) type in Python."""
  2.  
  3. from UserDict import DictMixin
  4.  
  5. class MyDict(DictMixin):
  6. # MyDict only needs to implement getitem, setitem, delitem and keys (at a
  7. # minimum) and UserDict will provide the rest of the standard dictionary
  8. # methods based on these four.
  9. #
  10. # getitem and delitem should raise KeyError if no item exists for the given
  11. # key. getitem, setitem and delitem should raise TypeError if the given key
  12. # is of the wrong type.
  13.  
  14. def __getitem__(self, key):
  15. ....
  16.  
  17. def __setitem__(self, key, item):
  18. ....
  19.  
  20. def __delitem__(self, key):
  21. ....
  22.  
  23. def keys(self):
  24. ....
  25.  
  26. # You can now use your class as if it was a dict, using the standard container
  27. # operators and dictionary methods.
  28.  
  29. d = MyDict()
  30. d[key] = value
  31. d.get(key)
  32. d.clear()
  33. etc.

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.