Skip to content

headers="keys" raises TypeError when rows are iterators #515

Backlog

Description

@BLUESKY477

When a row is an iterator (e.g. a map object or iter(list)), tabulate works with the default headers but raises TypeError with headers="keys".

Environment: tabulate 0.10.0, Python 3.12

Reproduction

from tabulate import tabulate

tabulate([iter([1, 2])], tablefmt="plain")                  # works
tabulate([iter([1, 2])], headers="keys", tablefmt="plain")  # TypeError

Actual: TypeError

Expected:

  0    1
  1    2

The README says the supported inputs include

list of lists or another iterable of iterables

and

If headers="keys", then the keys of a dictionary/dataframe, or column indices are used.

https://github.com/astanin/python-tabulate#usage

Likely cause: in _normalize_tabular_data, the column-index headers are computed with len(rows[0]) before rows are converted to lists (the list(r) conversion happens a few lines later), and iterators have no len():

elif headers == "keys" and len(rows) > 0:
# keys are column indices
headers = list(map(str, range(len(rows[0]))))

Converting the first row (or all rows) to a list before taking its length would fix it.

Found while testing the library with an automated exploration tool; the reproduction above was re-run on 0.10.0 before filing.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions