markcial
markcial

Reputation: 9323

Complete representation of a dict extended superclass

Given this code:

class XmlObj(dict):
    def __init__(self,xml,*args,**kwargs):
        super(dict,self).__init__(*args,**kwargs)
        if xml.firstChild.nodeName == '#text':
            self.__setattr__( 'text', xml.firstChild.nodeValue )
            return
        else:
            for node in xml.childNodes:
                if self.has_key( node.nodeName ):
                    item = self.__getitem__(node.nodeName)
                    if type( item ) is not type( [] ):
                        item = [item]
                        item.append( XmlObj( node ))
                    self.__setitem__(node.nodeName, item )
                else:
                    self.__setitem__(node.nodeName, XmlObj(node) )

    def __str__(self):
        if hasattr(self,'text'):
            return self.__getattribute__('text')
        else:
            return "%s"%super(dict,self).__str__()

text = """<?xml version="1.0"?><response><success>true</success><message>Metric List</message><page>1</page><rpp>50</rpp><total>9</total><pages>1</pages></response>"""
obj = XmlObj( parseString( text ).documentElement )
print obj
print obj['rpp']

>>> {u'rpp': {}, u'success': {}, u'pages': {}, u'message': {}, u'total': {}, u'page': {}}
>>> 50

I'd like to get :

>>> {u'rpp': '50', u'success': True, u'pages': 4, u'message': 'Some message', u'total': 90, u'page': 1}

I just wonder how Python handles the __repr__ call of the objects just to get the obj parameters inside display the text attribute instead the empty dict.

Upvotes: 1

Views: 97

Answers (1)

markcial
markcial

Reputation: 9323

Just after some googling finally found the answer, just for informational sake i' ll post the answer here

http://effbot.org/pyfaq/how-can-i-get-a-dictionary-to-display-its-keys-in-a-consistent-order.htm

class XmlObj(dict):
    def __init__(self,xml,*args,**kwargs):
        super(dict,self).__init__(*args,**kwargs)
        if xml.firstChild.nodeName == '#text':
            self.__setattr__( 'text', xml.firstChild.nodeValue )
            return
        else:
            for node in xml.childNodes:
                if self.has_key( node.nodeName ):
                    item = self.__getitem__(node.nodeName)
                    if type( item ) is not type( [] ):
                        item = [item]
                        item.append( XmlObj( node ))
                    self.__setitem__(node.nodeName, item )
                else:
                    self.__setitem__(node.nodeName, XmlObj(node) )

    def __repr__(self):
        if hasattr(self,'text'):
            return self.__getattribute__('text')
        else:
            result = ["%r: %r" % (key, self[key]) for key in sorted(self)]
            return "{" + ", ".join(result) + "}"

    __str__ = __repr__

thanks everybody anyways :)

Upvotes: 1

Related Questions