Skip to content

Instantly share code, notes, and snippets.

@seanh
Created November 12, 2009 11:12
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save seanh/232822 to your computer and use it in GitHub Desktop.
Save seanh/232822 to your computer and use it in GitHub Desktop.
Create a dict-like object with DictMixin (Python)
"""How to create a custom mappable container (dictionary-like) type in Python."""
from UserDict import DictMixin
class MyDict(DictMixin):
# MyDict only needs to implement getitem, setitem, delitem and keys (at a
# minimum) and UserDict will provide the rest of the standard dictionary
# methods based on these four.
#
# getitem and delitem should raise KeyError if no item exists for the given
# key. getitem, setitem and delitem should raise TypeError if the given key
# is of the wrong type.
def __getitem__(self, key):
....
def __setitem__(self, key, item):
....
def __delitem__(self, key):
....
def keys(self):
....
# You can now use your class as if it was a dict, using the standard container
# operators and dictionary methods.
d = MyDict()
d[key] = value
d.get(key)
d.clear()
etc.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment