Return to Snippet

Revision: 6614
at June 2, 2008 11:46 by chombee


Updated Code
"""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.

Revision: 6613
at June 2, 2008 11:45 by chombee


Initial Code
"""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.

Initial URL


Initial Description


Initial Title
Creating dictionary-like objects in Python using DictMixin

Initial Tags
python

Initial Language
Python