while studying the open source repo of Odoo I found a line of code that I don't understand like the following
[data] = self.read()
I really would like to know why would you put the variable in a list
It seems to ensure that [data]
is an iterable of one item and therefore unpacks the first value from self.read()
It cannot be assigned to a non-iterable
>>> [data] = 1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: cannot unpack non-iterable int object
Works for iterable types, though must have a length equal to one
>>> [data] = {'some':2}
>>> data
'some'
>>> [data] = {'foo':2, 'bar':3}
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: too many values to unpack (expected 1)
>>> [data] = [1]
>>> data
1
>>> [data] = [[1]]
>>> data
[1]
>>> [data] = [1, 2]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: too many values to unpack (expected 1)
>>> [data] = []
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: not enough values to unpack (expected 1, got 0)