Skip to content

Fix TypeError when rowalign is passed as tuple (#440) - #468

Open
thejedi433 wants to merge 1 commit into
astanin:masterfrom
thejedi433:fix/rowalign-tuple-typeerror
Open

thejedi433 wants to merge 1 commit into
astanin:masterfrom
thejedi433:fix/rowalign-tuple-typeerror

Conversation

@thejedi433

Copy link
Copy Markdown

Problem

Calling tabulate() with rowalign (or any alignment parameter) as a tuple raises TypeError:

from tabulate import tabulate
tabulate([['a', 'b']], rowalign=('center',), tablefmt='grid')
# TypeError: can only concatenate tuple (not "list") to tuple

This was reported in #440.

Root cause

_expand_iterable (line 2482 in tabulate/__init__.py) uses original + [default] * N. When original is a tuple, tuple + list raises TypeError.

def _expand_iterable(original, num_desired, default):
    if isinstance(original, Iterable) and not isinstance(original, str):
        return original + [default] * (num_desired - len(original))  # tuple + list -> boom

Fix

Two changes in _expand_iterable:

  1. Convert original to a list before concatenation — handles tuple, set, generator, and any other iterable uniformly.
  2. Add bytes to the exclusion list alongside str for consistency (a bytes value shouldn't be expanded element-wise either).
def _expand_iterable(original, num_desired, default):
    if isinstance(original, Iterable) and not isinstance(original, (str, bytes)):
        return list(original) + [default] * (num_desired - len(original))

This affects rowalign, colalign, numalign, stralign, numparse, maxcolwidths, and maxheadercolwidths — all of which flow through _expand_iterable.

Tests

Added test/test_rowalign_tuple.py with 8 tests covering:

  • Tuple rowalign no longer raises TypeError
  • Tuple and list inputs produce identical output
  • Partial tuples (fewer elements than rows) still pad correctly
  • Regression tests confirming list, None, and all other alignment parameters (colalign, numalign, stralign) work with tuples

All 314 existing tests still pass (60 skipped due to optional dependencies).

Scope

Minimal — two lines changed in _expand_iterable, no other behavior affected. No documentation or API changes.

The _expand_iterable helper function attempted to concatenate a tuple with a list
using the + operator, which raises TypeError in Python. This caused tabulate()
to fail when users passed alignment parameters (rowalign, colalign, numalign,
stralign) as tuples instead of lists.

Fix by converting the iterable to a list before concatenation. Also exclude bytes
from iterable check for consistency.

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant