Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: why __str__ not call recursive?

I have some troubles when convert dict to JSON object. I have this class:

class ServerResponse(object):

    status = None
    code = None
    message = None
    data = None

    OK_STATUS = True
    ERROR_STATUS = False

    OK_CODE = 200

    def __init__(self, status=OK_STATUS, code=OK_CODE, message=None, data=None, *args, **kwargs):
        self.status = status
        self.code = code
        self.message = message
        self.data = data

    def to_dict(self):
        fields = {
            "status": self.status,
            "code": self.code,
            "message": self.message,
            "data": str(self.data),
        }

        return fields

    def to_json(self):
        return json.dumps(self.to_dict())

    def __str__(self):
        return self.to_json()

I use this class for generate server answer.

from server_response import ServerResponse as Response
...
return_data = {}

for (name, content) in result.items():
    if not previous_hashes or client.is_data_change(previous_hashes[name], data['hash']):
        return_data[name] = Response(data=content)
    else:
        return_data[name] = Response(code=201, message="Data has not changed")

response = Response(data=return_data)
...
self.write(str(response))

In answer from server I get next JSON

{u'status': True, u'message': None, u'code': 200, u'data': u"{'client': <server_response.ServerResponse object at 0x14e9710>, 'service': <server_response.ServerResponse object at 0x14e90d0>}"}

Why __str__ function don't call recursively?

like image 363
polyn0m Avatar asked Nov 12 '13 18:11

polyn0m


1 Answers

From this program:

class Foo(object):
    def __repr__(self):
        return "REPR"

    def __str__(self):
        return "STR"

x = {}

x['client'] = Foo()

print str(x)
print repr(x)

You can see that dict always calls repr on its members, regardless of whether str or repr was used on the dict.

like image 175
Douglas Leeder Avatar answered Oct 15 '22 08:10

Douglas Leeder