Skip to content

Commit 36cf93d

Browse files
committed
Truncate the show_as_cell() method for prettier output.
We also print out some placeholder if str() is not available.
1 parent e4d9f8b commit 36cf93d

File tree

2 files changed

+37
-1
lines changed

2 files changed

+37
-1
lines changed

src/biocutils/show_as_cell.py

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,5 +22,14 @@ def show_as_cell(x: Any, indices: Sequence[int]) -> List[str]:
2222
"""
2323
output = []
2424
for i in indices:
25-
output.append(str(x[i]))
25+
try:
26+
candidate = str(x[i])
27+
if len(candidate) > 25:
28+
candidate = candidate[:20] + "..." # pick the first two characters, whatever.
29+
nl = candidate.find("\n")
30+
if nl >= 0:
31+
candidate = candidate[:nl] + "..."
32+
output.append(candidate)
33+
except:
34+
output.append("####")
2635
return output

tests/test_show_as_cell.py

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,33 @@
11
from biocutils import show_as_cell
2+
import numpy
23

34

45
def test_show_as_cell():
56
assert show_as_cell([1, 2, 3, 4], range(4)) == ["1", "2", "3", "4"]
67
assert show_as_cell([1, 2, 3, 4], [1, 3]) == ["2", "4"]
8+
9+
assert show_as_cell(["abcdefghijklmnopqrstuvwxy", "abcdefghijklmnopqrstuvwxyz"], [0,1]) == ["abcdefghijklmnopqrstuvwxy", "abcdefghijklmnopqrst..."]
10+
assert show_as_cell(["abcdefghijkl\nmnopqrstuvwxyz", "abc\ndefghijklmnopqrstuvwxyz"], [0,1]) == ["abcdefghijkl...", "abc..."]
11+
12+
13+
def test_show_as_cell_numpy():
14+
n1d = numpy.array([1,2,3,4,5])
15+
assert show_as_cell(n1d, [0, 1, 4]) == ["1", "2", "5"]
16+
17+
# Empty arrays are processed correctly.
18+
empty = numpy.ndarray((10, 0))
19+
assert show_as_cell(empty, [0, 1, 4]) == ["[]", "[]", "[]"]
20+
empty = numpy.ndarray((10, 20, 0))
21+
assert show_as_cell(empty, [0, 1, 2, 3]) == ["[]", "[]", "[]", "[]"]
22+
23+
# Arrays where all other extents are 1 are processed correctly.
24+
n1col = numpy.array([1,2,3,4,5]).reshape((5, 1))
25+
assert show_as_cell(n1col, [2, 3]) == ["[3]", "[4]"]
26+
n1col = numpy.array([1,2,3,4,5]).reshape((5, 1, 1))
27+
assert show_as_cell(n1col, [1, 4]) == ["[[2]]", "[[5]]"]
28+
29+
# Arrays other extents are > 1 are processed correctly.
30+
general = numpy.array([1,2,3,4,5,6]).reshape((3, 2))
31+
assert show_as_cell(general, [0, 2]) == ["[1 2]", "[5 6]"]
32+
general = numpy.array([1,2,3,4,5,6]).reshape((3, 2, 1))
33+
assert show_as_cell(general, [0, 2]) == ["[[1]...", "[[5]..."]

0 commit comments

Comments
 (0)