tr3buchet February 2016

In python, how do I cast a class object to a dict

Let's say I've got a simple class in python

class Wharrgarbl(object):
    def __init__(self, a, b, c, sum, version='old'):
        self.a = a
        self.b = b
        self.c = c
        self.sum = 6
        self.version = version

    def __int__(self):
        return self.sum + 9000

    def __what_goes_here__(self):
        return {'a': self.a, 'b': self.b, 'c': self.c}

I can cast it to an integer very easily

>>> w = Wharrgarbl('one', 'two', 'three', 6)
>>> int(w)
9006

Which is great! But, now I want to cast it to a dict in a similar fashion

>>> w = Wharrgarbl('one', 'two', 'three', 6)
>>> dict(w)
{'a': 'one', 'c': 'three', 'b': 'two'}

What do I need to define for this to work? I tried substituting both __dict__ and dict for __what_goes_here__, but dict(w) resulted in a TypeError: Wharrgarbl object is not iterable in both cases. I don't think simply making the class iterable will solve the problem. I also attempted many googles with as many different wordings of "python cast object to dict" as I could think of but couldn't find anything relevant :{

Also! Notice how calling w.__dict__ won't do what I want because it's going to contain w.version and w.sum. I want to customize the cast to dict in the same way that I can customize the cast to int by using def int(self).

I know that I could just do something like this

>>> w.__what_goes_here__()
{'a': 'one', 'c': 'three', 'b': 'two'}

But I am assuming there is a pythonic way to make dict(w) work since it is the same type of thing as int(w) or str(w). If there isn't a more pythonic way, that's fine too, just figured I'd ask. Oh! I guess since i

Answers


noisewaterphd February 2016

It's hard to say without knowing the whole context of the problem, but I would not override __iter__.

I would implement __what_goes_here__ on the class.

as_dict(self:
    d = {...whatever you need...}
    return d


Rick Teachey February 2016

You need to override ' __iter__'.

Like this, for example:

def __iter__(self):
    yield 'a', self.a
    yield 'b', self.b
    yield 'c', self.c

Now you can just do:

dict(my_object)

I would also suggest looking into the 'collections.abc' module. This answer might be helpful:

http://stackoverflow.com/a/27803404/2437514

Specifically, you'll want to look at the 'Mapping' and 'MutableMapping' objects. If you use that module and inherit your object from one of the dict-like abcs, you can cast your object to a dict just as you require.

As noted in the comments below: it's worth mentioning that doing this the abc way essentially turns your object class into a dict-like class. So everything you would be able to do with dict, you could do with your own class object. This may be, or may not be, desirable. It would also mean there would probably be little reason (because of duck typing) to bother casting your object to a dict in the first place.

Also consider looking at the numerical abcs in the numbers module:

https://docs.python.org/3/library/numbers.html

Since you're also casting your object to an int, it might make more sense to essentially turn your class into a full fledged int so that casting isn't necessary.

However, after thinking about this a bit more, I would very much consider the asdict way of doing things suggested by other answers. It does not appear that your object is really much of a collection. Using the iter or abc method could be confusing for others unless it is very obvious exactly which object members would and would not be iterated. <


Joran Beasley February 2016

something like this would probably work

class MyClass:
    def __init__(self,x,y,z):
       self.x = x
       self.y = y
       self.z = z
    def __iter__(self): #overridding this to return tuples of (key,value)
       return iter([('x',self.x),('y',self.y),('z',self.z)])

dict(MyClass(5,6,7)) # because dict knows how to deal with tuples of (key,value)


Garrett R February 2016

I think this will work for you.

class A(object):
    def __init__(self, a, b, c, sum, version='old'):
        self.a = a
        self.b = b
        self.c = c
        self.sum = 6
        self.version = version

    def __int__(self):
        return self.sum + 9000

    def __iter__(self):
        return self.__dict__.iteritems()

a = A(1,2,3,4,5)
print dict(a)

Output

{'a': 1, 'c': 3, 'b': 2, 'sum': 6, 'version': 5}


jpmc26 February 2016

There is no magic method that will do what you want. The answer is simply name it appropriately. asdict is a reasonable choice for a plain conversion to dict, inspired primarily by namedtuple. However, your method will obviously contain special logic that might not be immediately obvious from that name; you are returning only a subset of the class' state. If you can come up with with a slightly more verbose name that communicates the concepts clearly, all the better.

Other answers suggest using __iter__, but unless your object is truly iterable (represents a series of elements), this really makes little sense and constitutes an awkward abuse of the method. The fact that you want to filter out some of the class' state makes this approach even more dubious.

Post Status

Asked in February 2016
Viewed 2,355 times
Voted 5
Answered 5 times

Search




Leave an answer