Skip to content

Commit

Permalink
Fix tabulate col size in case of empty cell
Browse files Browse the repository at this point in the history
Previously, the size is no less than len(str(None)) == 4.
This commit also add type hint and docstring to the function.
  • Loading branch information
McSinyx committed Apr 6, 2020
1 parent eb865b4 commit 692b39c
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 14 deletions.
Empty file.
29 changes: 15 additions & 14 deletions src/pip/_internal/commands/list.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,10 @@
write_output,
)
from pip._internal.utils.packaging import get_installer
from pip._internal.utils.typing import MYPY_CHECK_RUNNING

if MYPY_CHECK_RUNNING:
from typing import Any, Iterable, List, Tuple

logger = logging.getLogger(__name__)

Expand Down Expand Up @@ -241,22 +245,19 @@ def output_package_listing_columns(self, data, header):
write_output(val)


def tabulate(vals):
# From pfmoore on GitHub:
# https://github.com/pypa/pip/issues/3651#issuecomment-216932564
assert len(vals) > 0

sizes = [0] * max(len(x) for x in vals)
for row in vals:
sizes = [max(s, len(str(c))) for s, c in zip_longest(sizes, row)]
def tabulate(rows):
# type: (Iterable[Iterable[Any]]) -> Tuple[List[str], List[int]]
"""Return a list of formatted rows and a list of column sizes.
result = []
for row in vals:
display = " ".join([str(c).ljust(s) if c is not None else ''
for s, c in zip_longest(sizes, row)])
result.append(display)
For example::
return result, sizes
>>> tabulate([['foobar', 2000], [0xdeadbeef]])
(['foobar 2000', '3735928559'], [10, 4])
"""
rows = [tuple(map(str, row)) for row in rows]
sizes = [max(map(len, col)) for col in zip_longest(*rows, fillvalue='')]
table = [" ".join(map(str.ljust, row, sizes)) for row in rows]
return table, sizes


def format_for_columns(pkgs, options):
Expand Down

0 comments on commit 692b39c

Please sign in to comment.