Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is a REST response content "magically" converted from 'list' to 'string'

Tags:

python

rest

>>> print type(a)
<type 'list'>
>>> response.content = a
>>> print type(response.content)
<type 'str'>

Could you explain me this "magic?" How is a converted from list to string?

response is an instance of rest_framework.response.Response.

like image 465
Tom Cruise Avatar asked Apr 29 '13 19:04

Tom Cruise


2 Answers

There are only a couple ways that you could have something like this happen. The most common reason is if response.content is implemented as some sort of descriptor, interesting things like this could happen. (The typical descriptor which would operate like this would be a property object). In this case, the property's getter would be returning a string. As a formal example:

class Foo(self):
    def __init__(self):
        self._x = 1

    @property
    def attribute_like(self):
        return str(self._x)

    @attribute_like.setter
    def attribute_like(self,value):
        self._x = value

f = Foo()
f.attribute_like = [1,2,3]
print type(f.attribute_like)
like image 113
mgilson Avatar answered Sep 28 '22 05:09

mgilson


I suppose that this class makes this conversion by means of defining __setattr__ method. You can read http://docs.python.org/2.7/reference/datamodel.html#customizing-attribute-access for more information.

like image 42
postman Avatar answered Sep 28 '22 06:09

postman