From 9a377857920c6cd7d8ef44a21c982579f18e4b2a Mon Sep 17 00:00:00 2001 From: thejedi433 Date: Tue, 24 Nov 2026 09:09:44 +0200 Subject: [PATCH] Fix TypeError for headers='keys' with iterator rows (#515) _normalize_tabular_data computed column-index headers via len(rows[0]) before rows were materialized to lists, so an iterable of iterators (map/iter/generator rows) crashed with TypeError: object of type 'list_iterator' has no len() even though the same input rendered fine with the default headers. Materialize rows[0] when it has no __len__ (no-op for list/ tuple rows, single-use-safe for generators whose rows are themselves iterators). 3 regression tests: iterator rows, generator-of-iterators, ragged iterator rows; verified red->green on the full suite (309 passed, 60 skipped). --- tabulate/__init__.py | 4 ++++ test/test_input.py | 24 ++++++++++++++++++++++++ 2 files changed, 28 insertions(+) diff --git a/tabulate/__init__.py b/tabulate/__init__.py index 12a2950..ad1ca3d 100644 --- a/tabulate/__init__.py +++ b/tabulate/__init__.py @@ -1571,6 +1571,10 @@ def _normalize_tabular_data(tabular_data, headers, showindex="default"): elif headers == "keys" and len(rows) > 0: # keys are column indices + if not hasattr(rows[0], "__len__"): + # iterator row: materialize it first so len() works + # (the general rows-to-lists conversion happens later) + rows[0] = list(rows[0]) headers = list(map(str, range(len(rows[0])))) # take headers from the first row if necessary diff --git a/test/test_input.py b/test/test_input.py index 3cc3237..bb410e5 100644 --- a/test/test_input.py +++ b/test/test_input.py @@ -87,6 +87,30 @@ def test_list_of_lists_keys(): assert_equal(expected, result) +def test_iterable_of_iterables_keys(): + "Input: an iterable of iterators with column indices as headers (issue #515)." + ii = [iter([1, 2]), iter([3, 4])] + expected = "\n".join([" 0 1", " 1 2", " 3 4"]) + result = tabulate(ii, headers="keys", tablefmt="plain") + assert_equal(expected, result) + + +def test_generator_of_iterators_keys(): + "Input: a generator of iterators (single-use rows) with column-index headers (issue #515)." + gen = (iter([r, r + 1]) for r in range(3)) + expected = "\n".join([" 0 1", " 0 1", " 1 2", " 2 3"]) + result = tabulate(gen, headers="keys", tablefmt="plain") + assert_equal(expected, result) + + +def test_iterable_of_iterables_keys_ragged(): + "Input: iterator rows of unequal length with column-index headers (issue #515)." + ii = [iter([1, 2, 3]), iter([4])] + expected = "\n".join([" 0 1 2", " 1 2 3", " 4"]) + result = tabulate(ii, headers="keys", tablefmt="plain") + assert_equal(expected, result) + + def test_dict_like(): "Input: a dict of iterables with keys as headers." # columns should be padded with None, keys should be used as headers