Search code examples
pythonabc

Python idiom for dict-able classes?


I want to do something like this:

class Dictable:
    def dict(self):
        raise NotImplementedError

class Foo(Dictable):
    def dict(self):
        return {'bar1': self.bar1, 'bar2': self.bar2}

Is there a more pythonic way to do this? For example, is it possible to overload the built-in conversion dict(...)? Note that I don't necessarily want to return all the member variables of Foo, I'd rather have each class decide what to return.

Thanks.


Solution

  • The Pythonic way depends on what you want to do. If your objects shouldn't be regarded as mappings in their own right, then a dict method is perfectly fine, but you shouldn't "overload" dict to handle dictables. Whether or not you need the base class depends on whether you want to do isinstance(x, Dictable); note that hasattr(x, "dict") would serve pretty much the same purpose.

    If the classes are conceptually mappings of keys to values, then implementing the Mapping protocol seems appropriate. I.e., you'd implement

    • __getitem__
    • __iter__
    • __len__

    and inherit from collections.Mapping to get the other methods. Then you get dict(Foo()) for free. Example:

    class Foo(Mapping):
        def __getitem__(self, key):
            if key not in ("bar1", "bar2"):
                raise KeyError("{} not found".format(repr(key))
            return getattr(self, key)
    
        def __iter__(self):
            yield "bar1"
            yield "bar2"
    
        def __len__(self):
            return 2