Search code examples
pythondictionaryextend

Extend python's dict functionality to user created classes


Is it possible to add dict functionality to user created classes?

ie:

class Foo(object):
    def __init__(self, x, y):
       self.x
       self.y
    def __dict__(self):
       return {'x': self.x, 'y': self.y}

f = Foo()
dict(f) <-- throws TypeError: iteration over non-sequence

Solution

  • The dict constructor expects either a mapping or an iterable of key/value pairs as a parameter, so your class needs to either implement the mapping protocol or be iterable.

    Here's an example how to got about the latter approach:

    class Foo(object):
        def __init__(self, x, y):
           self.x = x
           self.y = y
        def __iter__(self):
           return vars(self).iteritems()
    

    Example usage:

    >>> dict(Foo(2, 3))
    {'x': 2, 'y': 3}
    

    I don't know how useful this is, though. You could just do

    >>> vars(Foo(2, 3))
    {'x': 2, 'y': 3}
    

    which would work without implementing __iter__() on your class.