Search code examples
python-3.xodoo

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


Solution

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