[Django]-Python what does self[name] = value means?

5đź‘Ť

âś…

Taiga is based on django, which is where SimpleTemplateResponse comes from. It is a subclass of HttpResponse which is a dict-like object.

Now, the loop is checking first if there is a name headers that is not None, or False. If it is set, then it is assuming that headers is a dictionary, and looping through each key/value pair of the dictionary with iteritems. It then duplicates the same keys and values as properties of the class, with self[name] = value.

In effect, what this means is that if there is are headers, they are accessible directly in the class as keys.

Here is a simple example of what its doing:

>>> class MyFoo(object):
...     def __init__(self):
...         self._data = {}
...     def __setitem__(self, a, b):
...         self._data[a] = b
...     def __getitem__(self, a):
...         return self._data[a]
...     def __delitem__(self, a):
...         del self._data[a]
...     def populate(self, d):
...        if d:
...           for k,v in d.iteritems():
...               self[k] = v
...
>>> headers = {'User-Agent': 'Python/2.7.5'}
>>> a = MyFoo()
>>> a.populate(headers)
>>> a['User-Agent']
'Python/2.7.5'

You can see that MyFoo is a simple class, but it defines some special methods __setitem__, __getitem__, __delitem__. These methods let any object of the class act like a dictionary.

The populate method is doing what is being done in the loop in the original source; and once its run – all keys of the dictionary become keys of the resulting MyFoo object.

In the source of the HttpResponse class you’ll note the same __setitem__, __getitem__, __delitem__ are defined (scroll down to line 140).

👤Burhan Khalid

1đź‘Ť

Response class is implementing sequence protocol. That’s It’ll be having __setitem__ and __getitem__ magic methods defined in it, which will make it to behave like any sequence or dictionary.

1đź‘Ť

In Django HttpResponse has been implemented as a container (HTTP response class with dictionary-accessed headers)

More about containers..

In Python one can create a container objects by implementing certain magic methods..

A sample container for better understanding..

>>> class Container(object):
...     def __init__(self):
...         self.d = {}
...     def __setitem__(self, i, k):
...         print 'Setitem called for assignment!'
...         self.d[i] = k
...     def __getitem__(self, i):
...         print 'Getitem called for assignment!'
...         return self.d[i]
...     def __delitem__(self, i):
...         print 'Delitem called for assignment!'
...         del self.d[i]
... 

Since we’ve implemented __setitem__ for assiginment and __getitem__ for get and __delitem__ for deleting an item, now Container object supports all these three operations..

Assigning value to some attribute for Container object..

>>> obj = Container()
>>> obj[1] = 'Assigned 1'
Setitem called for assignment!

When ever we try to assign something to this container by calling like obj[--some_attr--] = value, python checks for __setitem__ method for this class and it’s developers duty to write their own logic where to store that values, whether it’s a dict or some other data structure..

Retrieving a value from the container…

>>> obj[1]
Getitem called for retrieving!
'Assigned 1'

When ever we try to retrieve something to from container by calling like obj[--some_attr--], python checks for __getitem__ method for this object and it’s developers duty to write their own logic to return or do some operation inside..

Delete value from the container..

>>> del obj[1]
Delitem called for deleting item!

When ever we try to delete something to from container by calling like del obj[--some_attr--], python checks for __delitem__ method for this object…

So where ever you see self[item] = value or self[item] or del self[item] is same as doing this with object.

👤gsb-eng

0đź‘Ť

Your SimpleTemplateResponse object (the parent class of Response) will have a __getitem__ and a __setitem__ method.

I don’t know what the __getitem__ or __setitem__ methods that are inherited from SimpleTemplateResponse will do, but I’m guessing that, in this case, it will return an attribute of a response object.

Essentially what you’re doing is setting a particular attribute of the Response object to the value based on the rules in the inherited __getitem__ and __setitem__ methods.

You can read more here.

-1đź‘Ť

A python class is behaving like a dictionary.
When you do:
self[“foo”] = 1234
You can access it like a normal attribute of self:
print(self.foo)
The same holds for functions. It is used to dynamically extend a class.

👤Pieter

Leave a comment