jazzband / tablib

Python Module for Tabular Datasets in XLS, CSV, JSON, YAML, &c.
https://tablib.readthedocs.io/
MIT License
4.56k stars 588 forks source link

Inserting column with insert_col fails if dataset contains 0 rows #583

Closed LukasK1 closed 3 months ago

LukasK1 commented 3 months ago

I am trying to add additional column to a Dataset that is created from a dictionary. I have headers defined separately. However, when dictionary is empty (no rows to export because how data is filtered) insert_col method fails with error:

File "/usr/local/lib/python3.10/site-packages/tablib/core.py", line 372, in _clean_col
    header = [col.pop(0)]
IndexError: pop from empty list

After looking in to the code of the method _clean_col, my guess, that if statement: https://github.com/jazzband/tablib/blob/4fd9a68c24a2a95fc471d0fc29a2a911b469f93f/src/tablib/core.py#L373-L376

should be opposite:

        if not self.headers:
            header = [col.pop(0)]
        else:
            header = []

or:

        if self.headers:
            header = []
        else:
            header = [col.pop(0)]
LukasK1 commented 3 months ago

To reproduce:

>>> from tablib import Dataset
>>> ds = Dataset()
>>> ds.headers = ["First", "Second", "Third"]
>>> ds.insert_col(1, [], header="Insert")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python3.10/site-packages/tablib/core.py", line 544, in insert_col
    col = self._clean_col(col)
  File "/usr/local/lib/python3.10/site-packages/tablib/core.py", line 372, in _clean_col
    header = [col.pop(0)]
IndexError: pop from empty list
claudep commented 3 months ago

Thanks for the report. See the patch I suggested to fix this issue. Please tell me what you think.

LukasK1 commented 3 months ago

Looks good to me.