flexablelib 2.0.6__cp313-cp313-win_amd64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
flexablelib/columns.py ADDED
@@ -0,0 +1,905 @@
1
+ from .cells import (
2
+ _center_cell,
3
+ _ljust_cell,
4
+ _rjust_cell,
5
+ _fljust_cell,
6
+ _add_cell_spacing
7
+ )
8
+ from .style_compositions import TableComposition
9
+ from .fast import visible_width
10
+ from .utils import (
11
+ is_some_instance,
12
+ IndexCounter,
13
+ ValuePlacer
14
+ )
15
+ from .options import (
16
+ DEFAULT_FILL_CHAR,
17
+ FLT_FILTER,
18
+ INT_FILTER,
19
+ EXP_FILTER,
20
+ COLUMN_ALIGNS
21
+ )
22
+
23
+ from typing import (
24
+ Any,
25
+ Dict,
26
+ List,
27
+ Tuple,
28
+ Union,
29
+ Generator
30
+ )
31
+ from collections import namedtuple
32
+
33
+ TypeNames = namedtuple(
34
+ 'TypeNames',
35
+ [
36
+ 'bool_',
37
+ 'str_',
38
+ 'int_',
39
+ 'float_',
40
+ 'bytes_',
41
+ 'none_type_',
42
+ 'index_counter_',
43
+ 'value_placer_',
44
+ ]
45
+ )
46
+
47
+
48
+ TYPE_NAMES = TypeNames(
49
+ bool_=bool.__name__,
50
+ str_=str.__name__,
51
+ int_=int.__name__,
52
+ float_=float.__name__,
53
+ bytes_=bytes.__name__,
54
+ none_type_=type(None).__name__,
55
+ index_counter_=IndexCounter.__name__,
56
+ value_placer_=ValuePlacer.__name__,
57
+ )
58
+
59
+
60
+ FLOAT_SEPARATOR = '.'
61
+
62
+
63
+ # Positions inside the ``(left, point, right)`` triple that describes how a
64
+ # float column is laid out around its decimal axis.
65
+ LEFT_SIDE_WIDTH = 0
66
+ POINT_WIDTH = 1
67
+ RIGHT_SIDE_WIDTH = 2
68
+
69
+
70
+ ALIGNMENTS_PER_TYPE = {
71
+ TYPE_NAMES.bool_: COLUMN_ALIGNS.right,
72
+ TYPE_NAMES.str_: COLUMN_ALIGNS.left,
73
+ TYPE_NAMES.int_: COLUMN_ALIGNS.right,
74
+ TYPE_NAMES.float_: COLUMN_ALIGNS.float,
75
+ TYPE_NAMES.bytes_: COLUMN_ALIGNS.bytes,
76
+ TYPE_NAMES.none_type_: COLUMN_ALIGNS.left,
77
+ }
78
+
79
+
80
+ CAN_WRAP_TYPES = [
81
+ TYPE_NAMES.str_,
82
+ TYPE_NAMES.none_type_,
83
+ TYPE_NAMES.value_placer_
84
+ ]
85
+
86
+
87
+ def __check_for_types_in_column(column_types: list,
88
+ accepted_types: list
89
+ ) -> bool:
90
+ """
91
+ Compares two list of type names.
92
+
93
+ Example::
94
+
95
+ __check_for_types_in_column(
96
+ column_types=['str', 'int'],
97
+ accepted_types=['str', 'int']
98
+ ) -> True
99
+ __check_for_types_in_column(
100
+ column_types=['str', 'int', 'float'],
101
+ accepted_types=['str', 'int']
102
+ ) -> False
103
+ """
104
+ for type_ in column_types:
105
+ if type_ not in accepted_types:
106
+ return False
107
+
108
+ return True
109
+
110
+
111
+ def __is_str_column(column_types: list) -> bool:
112
+ """
113
+ Receives a list of type names and returns True if
114
+ all of the names are one of those::
115
+
116
+ 'bool', 'str', 'int',
117
+ 'float', 'bytes', 'NoneType',
118
+ 'IndexCounter' 'ValuePlacer'
119
+ """
120
+ test = __check_for_types_in_column(
121
+ column_types=column_types,
122
+ accepted_types=list(TYPE_NAMES)
123
+ )
124
+ return test
125
+
126
+
127
+ def __is_byte_column(column_types: list) -> bool:
128
+ """
129
+ Receives a list of type names and returns True if
130
+ all of the names are one of those::
131
+
132
+ 'bytes', 'ValuePlacer'
133
+ """
134
+ test = __check_for_types_in_column(
135
+ column_types=column_types,
136
+ accepted_types=[
137
+ TYPE_NAMES.bytes_,
138
+ TYPE_NAMES.value_placer_
139
+ ]
140
+ )
141
+ return test
142
+
143
+
144
+ def __is_int_column(column_types: list) -> bool:
145
+ """
146
+ Receives a list of type names and returns True if
147
+ all of the names are one of those::
148
+
149
+ 'int', 'bool', 'ValuePlacer', 'IndexCounter'
150
+ """
151
+ test = __check_for_types_in_column(
152
+ column_types=column_types,
153
+ accepted_types=[
154
+ TYPE_NAMES.int_,
155
+ TYPE_NAMES.bool_,
156
+ TYPE_NAMES.value_placer_,
157
+ TYPE_NAMES.index_counter_
158
+ ]
159
+ )
160
+ return test
161
+
162
+
163
+ def __is_float_column(column_types: list) -> bool:
164
+ """
165
+ Receives a list of type names and returns True if
166
+ all of the names are one of those::
167
+
168
+ 'int', 'float', 'ValuePlacer'
169
+ """
170
+ test = __check_for_types_in_column(
171
+ column_types=column_types,
172
+ accepted_types=[
173
+ TYPE_NAMES.int_,
174
+ TYPE_NAMES.float_,
175
+ TYPE_NAMES.value_placer_,
176
+ ]
177
+ )
178
+ return test
179
+
180
+
181
+ def __is_bool_column(column_types: bool) -> bool:
182
+ """
183
+ Receives a list of type names and returns True if
184
+ all of the names are one of those::
185
+
186
+ 'bool', 'ValuePlacer'
187
+ """
188
+ test = __check_for_types_in_column(
189
+ column_types=column_types,
190
+ accepted_types=[
191
+ TYPE_NAMES.bool_,
192
+ TYPE_NAMES.value_placer_
193
+ ]
194
+ )
195
+ return test
196
+
197
+
198
+ def __is_none_type(column_types: list) -> bool:
199
+ """
200
+ Receives a list of type names and returns True if
201
+ all of the names are one of those::
202
+
203
+ 'NoneType', 'ValuePlacer'
204
+ """
205
+ test = __check_for_types_in_column(
206
+ column_types=column_types,
207
+ accepted_types=[
208
+ TYPE_NAMES.none_type_,
209
+ TYPE_NAMES.value_placer_
210
+ ]
211
+ )
212
+ return test
213
+
214
+
215
+ def __get_column_type(column_types):
216
+ """
217
+ Will return the type of the column depending
218
+ on what combination of types it has.
219
+
220
+ Examples::
221
+
222
+ __get_column_type(['str', 'int']) -> 'str'
223
+ __get_column_type(['ValuePlacer', 'int']) -> 'int'
224
+ __get_column_type(['float', 'int']) -> 'float'
225
+ __get_column_type(['NoneType', 'int']) -> 'str'
226
+ __get_column_type(['ValuePlacer', 'bool']) -> 'bool'
227
+ """
228
+ if __is_none_type(column_types):
229
+ return TYPE_NAMES.none_type_
230
+ # if __is_byte_column(column_types):
231
+ # return TYPE_NAMES.bytes_
232
+ if __is_bool_column(column_types):
233
+ return TYPE_NAMES.bool_
234
+ if __is_int_column(column_types):
235
+ return TYPE_NAMES.int_
236
+ if __is_float_column(column_types):
237
+ return TYPE_NAMES.float_
238
+ if __is_str_column(column_types):
239
+ return TYPE_NAMES.str_
240
+ else:
241
+ return TYPE_NAMES.none_type_
242
+
243
+
244
+ def __header_width(header: Union[Any, list, tuple]) -> int:
245
+ """
246
+ Returns the width of the header.
247
+ """
248
+ if is_some_instance(header, tuple, list):
249
+ # If it's wrapped, will be a tuple or list. To get
250
+ # the size, will get first the widths of all the sub-rows
251
+ # and the the max of them.
252
+ return (
253
+ max([visible_width(str(sub_row)) for sub_row in header])
254
+ )
255
+ else:
256
+ # If it's not wrapped, will be a string, so will only
257
+ # get it's width.
258
+ return visible_width(str(header))
259
+
260
+
261
+ def __get_single_column_width(column: dict,
262
+ show_headers: bool,
263
+ skip_rows: frozenset = frozenset()
264
+ ) -> Tuple[int, int]:
265
+ """
266
+ Will return the max size of the data in the column
267
+ and the header size.
268
+
269
+ Should receive a column with one of the following structures::
270
+
271
+ # WITH WRAPPED HEADER AND DATA
272
+ {
273
+ 'header': (('wrapped', 'header'), ...),
274
+ 'data': ('data', ('wrapped', 'cell'), ...)
275
+ }
276
+
277
+ # NO WRAPPER HEADER OR DATA
278
+ {
279
+ 'header': 'header1',
280
+ 'data': ('data', ...)
281
+ }
282
+
283
+ Returns::
284
+
285
+ (header_size: int, body_max_size: int)
286
+ """
287
+ head_size = 0
288
+ body_sizes = []
289
+ if show_headers:
290
+ # If headers will show, get them.
291
+ header = column['header']
292
+ head_size += __header_width(header)
293
+ for row_i, row in enumerate(column['data']):
294
+ # Rows that will not be rendered must not be measured. A hidden empty
295
+ # row still carries the missing value, and letting it through widened
296
+ # the column to fit text nobody would ever see -- issue #22.
297
+ if row_i in skip_rows:
298
+ continue
299
+ # The same principle as the header is applied here but for each cell.
300
+ # Every length will be added to the body_sizes list.
301
+ if is_some_instance(row, tuple, list):
302
+ body_sizes.append(
303
+ max([visible_width(str(sub_row)) for sub_row in row])
304
+ )
305
+ else:
306
+ body_sizes.append(visible_width(str(row)))
307
+
308
+ # And once more will get the max to get the length of the column.
309
+ # Every row may have been skipped, in which case the body contributes
310
+ # nothing and the header alone decides the width.
311
+ body_max_size = max(body_sizes) if body_sizes else 0
312
+
313
+ return head_size, body_max_size
314
+
315
+ def __split_float_cell(cell: Any) -> Union[Tuple[int, int, int], None]:
316
+ """
317
+ Measure one numeric cell of a float column, by side of the point.
318
+
319
+ Returns ``(left, point, right)`` for a float, ``(width, 0, 0)`` for an
320
+ integer, and ``None`` for anything that is not a number -- a missing
321
+ value, or text that landed in a numeric column.
322
+
323
+ Examples::
324
+
325
+ __split_float_cell('123.45') -> (3, 1, 2)
326
+ __split_float_cell('321111') -> (6, 0, 0)
327
+ __split_float_cell('missing') -> None
328
+ """
329
+ text = str(cell)
330
+
331
+ if FLT_FILTER(text) is not None:
332
+ left, point, right = text.partition(FLOAT_SEPARATOR)
333
+ return (
334
+ visible_width(left),
335
+ len(point),
336
+ visible_width(right),
337
+ )
338
+
339
+ if INT_FILTER(text) is not None:
340
+ # An integer aligns against the left side of the floats, so all of
341
+ # its width belongs there and it contributes no point and no
342
+ # decimals.
343
+ return visible_width(text), 0, 0
344
+
345
+ return None
346
+
347
+
348
+ def __measure_float_cell(cell: Any,
349
+ numeric_sides: List[int],
350
+ text_widths: List[int],
351
+ ) -> None:
352
+ """
353
+ Fold one cell into the running measurement of a float column.
354
+
355
+ Numbers widen ``numeric_sides``; anything else is recorded in
356
+ ``text_widths`` and measured whole. Wrapped cells (lists or tuples of
357
+ lines) are folded in line by line.
358
+ """
359
+ if is_some_instance(cell, tuple, list):
360
+ for sub_cell in cell:
361
+ __measure_float_cell(sub_cell, numeric_sides, text_widths)
362
+ return
363
+
364
+ sides = __split_float_cell(cell)
365
+ if sides is None:
366
+ text_widths.append(visible_width(str(cell)))
367
+ return
368
+
369
+ left, point, right = sides
370
+ numeric_sides[LEFT_SIDE_WIDTH] = max(numeric_sides[LEFT_SIDE_WIDTH], left)
371
+ numeric_sides[POINT_WIDTH] = max(numeric_sides[POINT_WIDTH], point)
372
+ numeric_sides[RIGHT_SIDE_WIDTH] = max(numeric_sides[RIGHT_SIDE_WIDTH], right)
373
+
374
+
375
+ def __get_float_column_width(column: dict,
376
+ show_headers: bool,
377
+ skip_rows: frozenset = frozenset()
378
+ ) -> Tuple[int, int, Tuple[int, int, int]]:
379
+ """
380
+ Will get the header size, body size and the max size of the sides
381
+ of a float column.
382
+
383
+ The numbers and the text are measured **separately** and only then
384
+ combined. A float column is as wide as the widest of three things: the
385
+ numbers laid out on their shared decimal axis, the widest non-numeric
386
+ cell, and the header. Whichever wins, the decimal axis is then pushed
387
+ right so the widest number's last decimal lands on the column's right
388
+ edge.
389
+
390
+ Measuring them together is what issue #23 was: a 15-character missing
391
+ value went into the left-hand slot, and the point and the decimals were
392
+ then added on top of it, making the column four characters wider than
393
+ anything in it. A correction existed but only fired for numbers that
394
+ came *after* the wide text, so the width depended on the row order.
395
+
396
+ Returns::
397
+
398
+ (head_size: int, total_width: int, sides: (left, point, right))
399
+
400
+ Example::
401
+
402
+ __get_float_column_width(
403
+ column={
404
+ 'header': ('Test', 'Results'),
405
+ 'data': (9.651, 3, 245.7, (3.5, ''), '?')
406
+ },
407
+ show_headers=False
408
+ )
409
+
410
+ Results in::
411
+
412
+ (0, 7, (3, 1, 3))
413
+
414
+ """
415
+ head_size = 0
416
+ if show_headers:
417
+ # If headers will show, get them.
418
+ header = column['header']
419
+ head_size += __header_width(header)
420
+
421
+ numeric_sides = [0, 0, 0]
422
+ text_widths = []
423
+
424
+ for row_i, row in enumerate(column['data']):
425
+ # Hidden rows must not contribute to the decimal-side widths either.
426
+ if row_i in skip_rows:
427
+ continue
428
+ __measure_float_cell(row, numeric_sides, text_widths)
429
+
430
+ point = numeric_sides[POINT_WIDTH]
431
+ right = numeric_sides[RIGHT_SIDE_WIDTH]
432
+ numeric_width = numeric_sides[LEFT_SIDE_WIDTH] + point + right
433
+
434
+ total_width = max(
435
+ numeric_width,
436
+ max(text_widths) if text_widths else 0,
437
+ head_size,
438
+ )
439
+
440
+ # Everything the numbers do not need goes to the left of the point, so
441
+ # the decimal axis sits as far right as the column allows and text cells
442
+ # right-align flush with the widest number.
443
+ sides = (total_width - point - right, point, right)
444
+
445
+ return head_size, total_width, sides
446
+
447
+
448
+ FloatExtents = namedtuple(
449
+ 'FloatExtents',
450
+ ['left', 'point', 'right', 'text']
451
+ )
452
+
453
+
454
+ def _is_numeric_cell(cell: Any) -> bool:
455
+ """
456
+ Whether a cell holds something that aligns on the decimal axis.
457
+
458
+ A wrapped cell never does: it is text that had to be broken over
459
+ several lines.
460
+ """
461
+ if is_some_instance(cell, tuple, list):
462
+ return False
463
+ return __split_float_cell(cell) is not None
464
+
465
+
466
+ def _float_extents(cells: Union[list, tuple],
467
+ skip_rows: frozenset = frozenset()
468
+ ) -> FloatExtents:
469
+ """
470
+ The raw extents of a float column, before any padding is applied.
471
+
472
+ ``left``/``point``/``right`` are what the *numbers* need around the
473
+ decimal axis and ``text`` is the widest non-numeric cell. Unlike the
474
+ sides reported by ``__get_float_column_width``, none of these has been
475
+ stretched to fill the column, which is what makes them the right input
476
+ for deciding how far a column may be narrowed: the integer digits are
477
+ the one part that cannot be given up.
478
+
479
+ Example::
480
+
481
+ _float_extents([9.651, 3, 245.7, 'missing_value__'])
482
+ -> FloatExtents(left=3, point=1, right=3, text=15)
483
+ """
484
+ numeric_sides = [0, 0, 0]
485
+ text_widths = []
486
+
487
+ for row_i, cell in enumerate(cells):
488
+ if row_i in skip_rows:
489
+ continue
490
+ __measure_float_cell(cell, numeric_sides, text_widths)
491
+
492
+ return FloatExtents(
493
+ left=numeric_sides[LEFT_SIDE_WIDTH],
494
+ point=numeric_sides[POINT_WIDTH],
495
+ right=numeric_sides[RIGHT_SIDE_WIDTH],
496
+ text=max(text_widths) if text_widths else 0,
497
+ )
498
+
499
+
500
+ def _round_float_cell(cell: Any, decimals: int) -> Any:
501
+ """
502
+ Re-render one numeric cell with ``decimals`` digits after the point.
503
+
504
+ Anything that is not a number is returned untouched -- a missing value
505
+ cannot be rounded, and neither can a wrapped cell. Integers are left
506
+ alone as well: they carry no decimals to give up, and padding them out
507
+ to some would only widen the column this is trying to narrow.
508
+
509
+ Examples::
510
+
511
+ _round_float_cell(9.651, 2) -> '9.65'
512
+ _round_float_cell(245.7, 0) -> '246'
513
+ _round_float_cell(3, 2) -> 3
514
+ _round_float_cell('n/a', 2) -> 'n/a'
515
+ """
516
+ text = str(cell)
517
+ if FLT_FILTER(text) is None or EXP_FILTER(text) is not None:
518
+ # An exponential says how big a number is, not how precise it is.
519
+ # Rounding 1.5e-05 to two decimals writes 0.00, which is a different
520
+ # claim entirely.
521
+ return cell
522
+
523
+ if decimals <= 0:
524
+ # No point either: a column with nothing after the point should not
525
+ # keep paying a character for one.
526
+ return format(float(text), '.0f')
527
+
528
+ return format(float(text), '.{0}f'.format(decimals))
529
+
530
+
531
+ def _column_widths(processed_columns: Dict[str, tuple],
532
+ column_type_names: dict,
533
+ show_headers: bool,
534
+ skip_rows: frozenset = frozenset()
535
+ ) -> Tuple[tuple, Union[None, dict]]:
536
+ """
537
+ Will return the widths of the columns. Float columns widths
538
+ are calculated by side of the point.
539
+
540
+ Returns::
541
+
542
+ (widths: tuple, float_column_widths: None | dict)
543
+
544
+ Example::
545
+
546
+ _column_widths(
547
+ processed_columns={
548
+ {'header': 'header1', 'data': ['data1', 'data2']},
549
+ {'header': 'header2', 'data': [1.2, 12.43]}
550
+ },
551
+ column_type_names={'header1': 'str', 'header2': 'float'},
552
+ )
553
+
554
+ Results in::
555
+
556
+ ((7, 7), {'header2': (4, 1, 2)})
557
+ """
558
+ # TODO add support for coloring codes
559
+
560
+ head_sizes = []
561
+ body_sizes = []
562
+ float_column_widths = None
563
+ for header, column in processed_columns.items():
564
+ if column_type_names[header] == TYPE_NAMES.float_:
565
+
566
+ # If it's a float column, get the body size,
567
+ # header size and float sizes.
568
+ head_size, body_size, decimal_sides = __get_float_column_width(
569
+ column,
570
+ show_headers,
571
+ skip_rows
572
+ )
573
+
574
+ # Save header and body size separately to prevent
575
+ # the header size # from being added to the
576
+ # calculation in case of turning off the headers.
577
+ head_sizes.append(head_size)
578
+ body_sizes.append(body_size)
579
+
580
+ # Save float column sizes as a dict.
581
+ try:
582
+ float_column_widths[header] = decimal_sides
583
+ except TypeError:
584
+ float_column_widths = {header: decimal_sides}
585
+
586
+ else:
587
+
588
+ # If it's not a float column, get the body and header size,
589
+ # and save them separately.
590
+ head_size, body_size = __get_single_column_width(
591
+ column,
592
+ show_headers,
593
+ skip_rows
594
+ )
595
+ head_sizes.append(head_size)
596
+ body_sizes.append(body_size)
597
+
598
+ if show_headers:
599
+ # Get the max width between the header and body sizes if the header
600
+ # is set to show.
601
+ widths = list(map(lambda x, y: max(x, y), head_sizes, body_sizes))
602
+
603
+ else:
604
+ # Only the body sizes if the header is not set to show.
605
+ widths = body_sizes
606
+
607
+ return widths, float_column_widths
608
+
609
+
610
+ def _typify_column(column: Union[list, tuple],
611
+ index_column=False,
612
+ ) -> Tuple[Tuple[str], str, str]:
613
+ """
614
+ Get the types of the column and it's alignments.
615
+
616
+ Uses the ``__name__`` property to get the type class' name
617
+ traversing the column and using the ``type`` class do so::
618
+
619
+ type(data).__name__
620
+
621
+ Returns::
622
+
623
+ (identified_types: tuple, column_type: str, column_alignment: str)
624
+ """
625
+ identified_types = []
626
+
627
+ for row in column:
628
+ if index_column:
629
+ # If it is the index column, it will be took in count as int.
630
+ identified_types.append(int.__name__)
631
+ elif row != '':
632
+ # Get the type as long as is not an empty string.
633
+ identified_types.append(type(row).__name__)
634
+ else:
635
+ # If it's an empty string, should be considered as None.
636
+ identified_types.append(type(None).__name__)
637
+
638
+ # Get the type of the column.
639
+ column_type = __get_column_type(identified_types)
640
+ # Using the column type, get the alignment.
641
+ column_alignment = ALIGNMENTS_PER_TYPE[column_type]
642
+ identified_types = tuple(identified_types)
643
+
644
+ return identified_types, column_type, column_alignment
645
+
646
+
647
+ def __align_single_cell(cell: Union[Any, List[Any], Tuple[Any]],
648
+ col_width: int,
649
+ to_where: str,
650
+ margin: int,
651
+ float_column_sizes: list=None
652
+ ) -> Union[str, Tuple[str]]:
653
+ """
654
+ Will add space to the cell to align it.
655
+
656
+ Returns::
657
+
658
+ new_cell: str | tuple
659
+
660
+ Examples::
661
+
662
+ __align_single_cell(
663
+ cell="data1",
664
+ col_width=7,
665
+ to_where="l",
666
+ margin=1,
667
+ float_column_sizes=None
668
+ )
669
+ __align_single_cell(
670
+ cell="missing_value__",
671
+ col_width=15,
672
+ to_where="f",
673
+ margin=1,
674
+ float_column_sizes=(10, 1, 4)
675
+ )
676
+ __align_single_cell(
677
+ cell=12.4325,
678
+ col_width=15,
679
+ to_where="f",
680
+ margin=1,
681
+ float_column_sizes=(10, 1, 4)
682
+ )
683
+ __align_single_cell(
684
+ cell=111.22,
685
+ col_width=15,
686
+ to_where="f",
687
+ margin=1,
688
+ float_column_sizes=(10, 1, 4)
689
+ )
690
+
691
+ Results in::
692
+
693
+ ' data1 '
694
+ ' missing_value__ '
695
+ ' 12.4325 '
696
+ ' 111.22 '
697
+ """
698
+ new_cell = cell
699
+ if to_where == COLUMN_ALIGNS.left:
700
+ # Adjust the cell to the left.
701
+ new_cell = _ljust_cell(
702
+ cell,
703
+ col_width,
704
+ DEFAULT_FILL_CHAR
705
+ )
706
+ elif to_where == COLUMN_ALIGNS.center:
707
+ # Adjust the cell to the center.
708
+ new_cell = _center_cell(
709
+ cell,
710
+ col_width,
711
+ DEFAULT_FILL_CHAR
712
+ )
713
+ elif to_where == COLUMN_ALIGNS.right:
714
+ # Adjust the cell to the right.
715
+ new_cell = _rjust_cell(
716
+ cell,
717
+ col_width,
718
+ DEFAULT_FILL_CHAR
719
+ )
720
+ elif to_where == COLUMN_ALIGNS.float:
721
+ # Adjust the cell as a float.
722
+ new_cell = _fljust_cell(
723
+ cell,
724
+ col_width,
725
+ float_column_sizes,
726
+ DEFAULT_FILL_CHAR,
727
+ )
728
+ elif to_where == COLUMN_ALIGNS.bytes:
729
+ # Bytes alignment is left-justified (see INDICATOR_RELATIONS). Without
730
+ # this branch the raw cell reaches _add_cell_spacing and TypeErrors on
731
+ # non-str values when callers set *_align / col_alignment to 'b'.
732
+ new_cell = _ljust_cell(
733
+ cell,
734
+ col_width,
735
+ DEFAULT_FILL_CHAR,
736
+ )
737
+ else:
738
+ # Unknown alignment code: still stringify and left-pad so compose()
739
+ # never blows up on a typo or a future alignment name.
740
+ new_cell = _ljust_cell(
741
+ cell,
742
+ col_width,
743
+ DEFAULT_FILL_CHAR,
744
+ )
745
+ # Add the margin (if any) to the cell.
746
+ new_cell = _add_cell_spacing(new_cell, margin, margin, 0)
747
+
748
+ if is_some_instance(new_cell, tuple, list):
749
+ return tuple(new_cell)
750
+ else:
751
+ return new_cell
752
+
753
+
754
+ def __align_one_column(column: Union[list, tuple],
755
+ column_i: int,
756
+ col_alignments: list,
757
+ col_widths: list,
758
+ margin: int,
759
+ float_column_sizes: dict = None
760
+ ) -> Generator[str, None, None]:
761
+ """
762
+ Aligns a single row of a column.
763
+
764
+ Yields::
765
+
766
+ aligned_column: Generator[str]
767
+ """
768
+ aligned_column = []
769
+ to_where = col_alignments[column_i]
770
+ col_width = col_widths[column_i]
771
+ for cell in column:
772
+ aligned_column.append(
773
+ __align_single_cell(
774
+ cell,
775
+ col_width,
776
+ to_where,
777
+ margin,
778
+ float_column_sizes
779
+ )
780
+ )
781
+
782
+ yield tuple(aligned_column)
783
+
784
+
785
+ def _align_columns(style_composition: TableComposition,
786
+ columns: Union[List[Union[list, tuple]], Tuple[Union[list, tuple]]],
787
+ headers: Union[list, tuple],
788
+ col_alignments: List[str],
789
+ col_widths: List[int],
790
+ empty_columns_i: List[int],
791
+ show_empty: bool,
792
+ float_cols_sizes: dict
793
+ ) -> Generator[str, None, None]:
794
+ """
795
+ Aligns the columns and adds margin to the cells.
796
+ """
797
+ # The margin that the selected style has.
798
+ margin = style_composition.margin
799
+
800
+ for column_i, column in enumerate(columns):
801
+
802
+ # Align only the columns that are shown.
803
+ if (not show_empty and column_i not in empty_columns_i
804
+ ) or show_empty:
805
+
806
+ # Get the header of the column.
807
+ header = headers[column_i]
808
+
809
+ # Try to get the float sizes (if it is a float column).
810
+ try:
811
+ float_column_sizes = float_cols_sizes[header]
812
+ except KeyError:
813
+ float_column_sizes = None
814
+
815
+ # Align the column.
816
+ yield from __align_one_column(
817
+ column,
818
+ column_i,
819
+ col_alignments,
820
+ col_widths,
821
+ margin,
822
+ float_column_sizes
823
+ )
824
+
825
+ else:
826
+ continue
827
+
828
+
829
+ def __align_one_header(column: Union[str, list, tuple],
830
+ col_width: int,
831
+ to_where: str,
832
+ margin: int,
833
+ float_column_sizes: dict
834
+ ) -> Union[str, Tuple[str]]:
835
+ """
836
+ Aligns a single cell of the header.
837
+ """
838
+ # Check if it's a wrapped cell.
839
+ if is_some_instance(column, tuple, list):
840
+ # Apply to each sub-row.
841
+ yield tuple(map(
842
+ lambda cell: __align_single_cell(
843
+ cell,
844
+ col_width,
845
+ to_where,
846
+ margin,
847
+ float_column_sizes
848
+ ),
849
+ column
850
+ ))
851
+ else:
852
+ # Apply to the cell.
853
+ yield __align_single_cell(column, col_width, to_where, margin)
854
+
855
+
856
+ def _align_headers(style_composition: TableComposition,
857
+ headers: Union[list, tuple],
858
+ col_alignments: List[str],
859
+ col_widths: List[int],
860
+ empty_columns_i: List[int],
861
+ show_empty: bool,
862
+ float_cols_sizes: dict):
863
+ """
864
+ Will align the headers using the provided column alignments.
865
+ """
866
+
867
+ # The margin that the selected style has.
868
+ margin = style_composition.margin
869
+
870
+ for column_i, column in enumerate(headers):
871
+ # Get the alignment of the current column.
872
+ to_where = col_alignments[column_i]
873
+
874
+ # Get the width that the current column should have.
875
+ col_width = col_widths[column_i]
876
+
877
+ # Get the column name to try to get the float sizes (in case of the
878
+ # column a float column).
879
+ if is_some_instance(column, tuple, list):
880
+ # If it's wrapped, it will come splitted
881
+ col_name = ''.join(column)
882
+ else:
883
+ col_name = column
884
+ try:
885
+ float_column_sizes = float_cols_sizes[col_name]
886
+ except KeyError:
887
+ float_column_sizes = None
888
+
889
+ # Only align the headers if its column is shown.
890
+ if (not show_empty and column_i not in empty_columns_i
891
+ ) or show_empty:
892
+ yield from __align_one_header(
893
+ column,
894
+ col_width,
895
+ to_where,
896
+ margin,
897
+ float_column_sizes
898
+ )
899
+ else:
900
+ continue
901
+
902
+
903
+
904
+ if __name__ == '__main__':
905
+ print('Hey! This is not to be executed.')