Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

declaring a python variable in a list [data] = self.read()?

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()

found there https://github.com/odoo/odoo/blob/8f297c9d5f6d31370797d64fee5ca9d779f14b81/addons/hr_holidays/wizard/hr_holidays_summary_department.py#L25

I really would like to know why would you put the variable in a list

like image 274
kerbrose Avatar asked Nov 17 '25 10:11

kerbrose


1 Answers

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)
like image 115
OneCricketeer Avatar answered Nov 19 '25 09:11

OneCricketeer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!