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.
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
dictmethod is perfectly fine, but you shouldn’t “overload”dictto handle dictables. Whether or not you need the base class depends on whether you want to doisinstance(x, Dictable); note thathasattr(x, "dict")would serve pretty much the same purpose.If the classes are conceptually mappings of keys to values, then implementing the
Mappingprotocol seems appropriate. I.e., you’d implement__getitem____iter____len__and inherit from
collections.Mappingto get the other methods. Then you getdict(Foo())for free. Example: