在研究Odoo的开源回购时,我发现了一行我不理解的代码,比如下面的
[data] = self.read()
在那里找到的https://github.com/odoo/odoo/blob/8f297c9d5f6d31370797d64fee5ca9d779f14b81/addons/hr_holidays/wizard/hr_holidays_summary_department.py#L25
我真的很想知道你为什么要把变量放在列表中
似乎可以确保[data]
是一个项的可迭代项,因此可以从self.read()
中拆包第一个值
不能将其分配给不可迭代的
>>> [data] = 1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: cannot unpack non-iterable int object
适用于可迭代类型,但长度必须等于一个
>>> [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)