Skip to content

tea_tasting.utils #

Useful functions and classes.

check_scalar(value, name='value', *, typ=None, ge=None, gt=None, le=None, lt=None, ne=None, in_=None) #

Check if a scalar parameter meets specified type and value constraints.

Parameters:

Name Type Description Default
value R

Parameter value.

required
name str

Parameter name.

'value'
typ object

Acceptable data types.

None
ge object

If not None, check that parameter value is greater than or equal to ge.

None
gt object

If not None, check that parameter value is greater than gt.

None
le object

If not None, check that parameter value is less than or equal to le.

None
lt object

If not None, check that parameter value is less than lt.

None
ne object

If not None, check that parameter value is not equal to ne.

None
in_ object

If not None, check that parameter value is in in_.

None

Returns:

Type Description
R

Parameter value.

Source code in src/tea_tasting/utils.py
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
def check_scalar(  # noqa: PLR0913
    value: R,
    name: str = "value",
    *,
    typ: object = None,
    ge: object = None,
    gt: object = None,
    le: object = None,
    lt: object = None,
    ne: object = None,
    in_: object = None,
) -> R:
    """Check if a scalar parameter meets specified type and value constraints.

    Args:
        value: Parameter value.
        name: Parameter name.
        typ: Acceptable data types.
        ge: If not `None`, check that parameter value is greater than
            or equal to `ge`.
        gt: If not `None`, check that parameter value is greater than `gt`.
        le: If not `None`, check that parameter value is less than or equal to `le`.
        lt: If not `None`, check that parameter value is less than `lt`.
        ne: If not `None`, check that parameter value is not equal to `ne`.
        in_: If not `None`, check that parameter value is in `in_`.

    Returns:
        Parameter value.
    """
    if typ is not None and not isinstance(value, typ):  # type: ignore
        raise TypeError(f"{name} must be an instance of {typ}.")
    if ge is not None and value < ge:
        raise ValueError(f"{name} == {value}, must be >= {ge}.")
    if gt is not None and value <= gt:
        raise ValueError(f"{name} == {value}, must be > {gt}.")
    if le is not None and value > le:
        raise ValueError(f"{name} == {value}, must be <= {le}.")
    if lt is not None and value >= lt:
        raise ValueError(f"{name} == {value}, must be < {lt}.")
    if ne is not None and value == ne:
        raise ValueError(f"{name} == {value}, must be != {ne}.")
    if in_ is not None and value not in in_:
        raise ValueError(f"{name} == {value}, must be in {in_}.")
    return value

auto_check(value, name) #

Automatically check a parameter's type and value based on its name.

The following parameter names are supported: "alpha", "alternative", "confidence_level", "correction", "equal_var", "n_obs", "n_resamples", "power", "ratio", "rng", "use_t".

Parameters:

Name Type Description Default
value R

Parameter value.

required
name str

Parameter name.

required

Returns:

Type Description
R

Parameter value.

Source code in src/tea_tasting/utils.py
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
def auto_check(value: R, name: str) -> R:  # noqa: C901, PLR0912
    """Automatically check a parameter's type and value based on its name.

    The following parameter names are supported: `"alpha"`, `"alternative"`,
    `"confidence_level"`, `"correction"`, `"equal_var"`, `"n_obs"`,
    `"n_resamples"`, `"power"`, `"ratio"`, `"rng"`, `"use_t"`.

    Args:
        value: Parameter value.
        name: Parameter name.

    Returns:
        Parameter value.
    """
    if name == "alpha":
        check_scalar(value, name, typ=float, gt=0, lt=1)
    if name == "alternative":
        check_scalar(value, name, typ=str, in_={"two-sided", "greater", "less"})
    elif name == "confidence_level":
        check_scalar(value, name, typ=float, gt=0, lt=1)
    elif name == "correction":
        check_scalar(value, name, typ=bool)
    elif name == "equal_var":
        check_scalar(value, name, typ=bool)
    elif name == "n_obs":
        check_scalar(value, name, typ=int | Sequence | None)
        if isinstance(value, int):
            check_scalar(value, name, gt=1)
        if isinstance(value, Sequence):
            for val in value:
                check_scalar(val, name, typ=int, gt=1)
    elif name == "n_resamples":
        check_scalar(value, name, typ=int, gt=0)
    elif name == "power":
        check_scalar(value, name, typ=float, gt=0, lt=1)
    elif name == "ratio":
        check_scalar(value, name, typ=float | int, gt=0)
    elif name == "rng":
        check_scalar(
            value,
            name,
            typ=int | np.random.Generator | np.random.SeedSequence | None,
        )
    elif name == "use_t":
        check_scalar(value, name, typ=bool)
    return value

format_num(val, sig=3, *, pct=False, nan='-', inf='∞', fixed_point_range=(0.001, 10000000), thousands_sep=None, decimal_point=None) #

Format a number according to specified formatting rules.

Parameters:

Name Type Description Default
val float | int | None

Number to format.

required
sig int

Number of significant digits.

3
pct bool

If True, format as a percentage.

False
nan str

Replacement for None and nan values.

'-'
inf str

Replacement for infinite values.

'∞'
fixed_point_range tuple[float | None, float | None]

The range within which the number is formatted as fixed point. Number outside of the range is formatted as exponential. None means no boundary.

(0.001, 10000000)
thousands_sep str | None

Thousands separator. If None, the value from locales is used.

None
decimal_point str | None

Decimal point symbol. If None, the value from locales is used.

None

Returns:

Type Description
str

Formatted number.

Source code in src/tea_tasting/utils.py
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
def format_num(
    val: float | int | None,
    sig: int = 3,
    *,
    pct: bool = False,
    nan: str = "-",
    inf: str = "∞",
    fixed_point_range: tuple[float | None, float | None] = (0.001, 10_000_000),
    thousands_sep: str | None = None,
    decimal_point: str | None = None,
) -> str:
    """Format a number according to specified formatting rules.

    Args:
        val: Number to format.
        sig: Number of significant digits.
        pct: If `True`, format as a percentage.
        nan: Replacement for `None` and `nan` values.
        inf: Replacement for infinite values.
        fixed_point_range: The range within which the number is formatted
            as fixed point.
            Number outside of the range is formatted as exponential.
            `None` means no boundary.
        thousands_sep: Thousands separator. If `None`, the value from locales is used.
        decimal_point: Decimal point symbol. If `None`, the value from locales is used.

    Returns:
        Formatted number.
    """
    if val is None or math.isnan(val):
        return nan

    if math.isinf(val):
        return inf if val > 0 else "-" + inf

    if pct:
        val = val * 100

    if (
        (fixed_point_range[0] is not None and abs(val) < fixed_point_range[0]) or
        (fixed_point_range[1] is not None and abs(val) >= fixed_point_range[1])
    ):
        precision = max(0, sig - 1)
        typ = "e" if val != 0 else "f"
    else:
        precision = max(0, sig - 1 - math.floor(math.log10(abs(val))))
        val = round(val, precision)
        # Repeat in order to format 99.999 as "100", not "100.0".
        precision = max(0, sig - 1 - math.floor(math.log10(abs(val))))
        typ = "f"

    result = format(val, f"_.{precision}{typ}")

    if thousands_sep is None:
        thousands_sep = locale.localeconv().get("thousands_sep", "_")  # type: ignore
    if thousands_sep != "_":
        result = result.replace("_", thousands_sep)

    if decimal_point is None:
        decimal_point = locale.localeconv().get("decimal_point", ".")  # type: ignore
    if decimal_point != ".":
        result = result.replace(".", decimal_point)

    if pct:
        return result + "%"

    return result

get_and_format_num(data, key) #

Get and format dictionary value.

Formatting rules:

  • If a name starts with "rel_" or equals to "power" consider it a percentage value. Round percentage values to 2 significant digits, multiply by 100 and add "%".
  • Round other values to 3 significant values.
  • If value is less than 0.001 or is greater than or equal to 10_000_000, format it in exponential presentation.
  • If a name ends with "_ci", consider it a confidence interval. Look up for attributes "{name}_lower" and "{name}_upper", and format the interval as "[{lower_bound}, {upper_bound}]".

Parameters:

Name Type Description Default
data dict[str, object]

Dictionary.

required
key str

Key.

required

Returns:

Type Description
str

Formatted value.

Source code in src/tea_tasting/utils.py
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
def get_and_format_num(data: dict[str, object], key: str) -> str:
    """Get and format dictionary value.

    Formatting rules:

    - If a name starts with `"rel_"` or equals to `"power"` consider it
        a percentage value. Round percentage values to 2 significant digits,
        multiply by `100` and add `"%"`.
    - Round other values to 3 significant values.
    - If value is less than `0.001` or is greater than or equal to `10_000_000`,
        format it in exponential presentation.
    - If a name ends with `"_ci"`, consider it a confidence interval.
        Look up for attributes `"{name}_lower"` and `"{name}_upper"`,
        and format the interval as `"[{lower_bound}, {upper_bound}]"`.

    Args:
        data: Dictionary.
        key: Key.

    Returns:
        Formatted value.
    """
    if key.endswith("_ci"):
        ci_lower = get_and_format_num(data, key + "_lower")
        ci_upper = get_and_format_num(data, key + "_upper")
        return f"[{ci_lower}, {ci_upper}]"

    val = data.get(key)
    if not isinstance(val, float | int | None):
        return str(val)

    sig, pct = (2, True) if key.startswith("rel_") or key == "power" else (3, False)
    return format_num(val, sig=sig, pct=pct)

DictsReprMixin #

Bases: ABC

Representation and conversion of a sequence of dictionaries.

Default formatting rules:

  • If a name starts with "rel_" or equals to "power" consider it a percentage value. Round percentage values to 2 significant digits, multiply by 100 and add "%".
  • Round other values to 3 significant values.
  • If value is less than 0.001 or is greater than or equal to 10_000_000, format it in exponential presentation.
  • If a name ends with "_ci", consider it a confidence interval. Look up for attributes "{name}_lower" and "{name}_upper", and format the interval as "[{lower_bound}, {upper_bound}]".

to_dicts() abstractmethod #

Convert the object to a sequence of dictionaries.

Source code in src/tea_tasting/utils.py
321
322
323
@abc.abstractmethod
def to_dicts(self) -> Sequence[dict[str, object]]:
    """Convert the object to a sequence of dictionaries."""

to_arrow() #

Convert the object to a PyArrow Table.

Source code in src/tea_tasting/utils.py
325
326
327
328
@_cache_method
def to_arrow(self) -> pa.Table:
    """Convert the object to a PyArrow Table."""
    return pa.Table.from_pylist(self.to_dicts())

to_pandas() #

Convert the object to a Pandas DataFrame.

Source code in src/tea_tasting/utils.py
330
331
332
333
334
@_cache_method
def to_pandas(self) -> pd.DataFrame:
    """Convert the object to a Pandas DataFrame."""
    import pandas as pd  # noqa: PLC0415
    return pd.DataFrame.from_records(self.to_dicts())

to_polars() #

Convert the object to a Polars DataFrame.

Source code in src/tea_tasting/utils.py
336
337
338
339
340
@_cache_method
def to_polars(self) -> pl.DataFrame:
    """Convert the object to a Polars DataFrame."""
    import polars as pl  # noqa: PLC0415
    return pl.from_dicts(self.to_dicts())

to_pretty_dicts(keys=None, formatter=get_and_format_num, *, max_rows=None) #

Convert the object to a list of dictionaries with formatted values.

Default formatting rules:

  • If a name starts with "rel_" or equals to "power" consider it a percentage value. Round percentage values to 2 significant digits, multiply by 100 and add "%".
  • Round other values to 3 significant values.
  • If value is less than 0.001 or is greater than or equal to 10_000_000, format it in exponential presentation.
  • If a name ends with "_ci", consider it a confidence interval. Look up for attributes "{name}_lower" and "{name}_upper", and format the interval as "[{lower_bound}, {upper_bound}]".

Parameters:

Name Type Description Default
keys Sequence[str] | None

Keys to convert. If a key is not defined in the dictionary it's assumed to be None.

None
formatter Callable[[dict[str, object], str], str]

Custom formatter function. It should accept a dictionary of metric result attributes and an attribute name, and return a formatted attribute value.

get_and_format_num
max_rows int | None

Maximum number of rows to convert. If None, the default value will be used. If 0 or less, all rows will be converted.

None

Returns:

Type Description
list[dict[str, str]]

List of dictionaries with formatted values.

Source code in src/tea_tasting/utils.py
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
def to_pretty_dicts(
    self,
    keys: Sequence[str] | None = None,
    formatter: Callable[[dict[str, object], str], str] = get_and_format_num,
    *,
    max_rows: int | None = None,
) -> list[dict[str, str]]:
    """Convert the object to a list of dictionaries with formatted values.

    Default formatting rules:

    - If a name starts with `"rel_"` or equals to `"power"` consider it
        a percentage value. Round percentage values to 2 significant digits,
        multiply by `100` and add `"%"`.
    - Round other values to 3 significant values.
    - If value is less than `0.001` or is greater than or equal to `10_000_000`,
        format it in exponential presentation.
    - If a name ends with `"_ci"`, consider it a confidence interval.
        Look up for attributes `"{name}_lower"` and `"{name}_upper"`,
        and format the interval as `"[{lower_bound}, {upper_bound}]"`.

    Args:
        keys: Keys to convert. If a key is not defined in the dictionary
            it's assumed to be `None`.
        formatter: Custom formatter function. It should accept a dictionary
            of metric result attributes and an attribute name, and return
            a formatted attribute value.
        max_rows: Maximum number of rows to convert.
            If `None`, the default value will be used.
            If `0` or less, all rows will be converted.

    Returns:
        List of dictionaries with formatted values.
    """
    pretty_dicts, _, _ = self._to_pretty_dicts(
        keys,
        formatter,
        max_rows=max_rows,
        escape_markdown=False,
    )
    return pretty_dicts

to_string(keys=None, formatter=get_and_format_num, *, max_rows=None, align=None, table_format='plain') #

Convert the object to a string.

Default formatting rules:

  • If a name starts with "rel_" or equals to "power" consider it a percentage value. Round percentage values to 2 significant digits, multiply by 100 and add "%".
  • Round other values to 3 significant values.
  • If value is less than 0.001 or is greater than or equal to 10_000_000, format it in exponential presentation.
  • If a name ends with "_ci", consider it a confidence interval. Look up for attributes "{name}_lower" and "{name}_upper", and format the interval as "[{lower_bound}, {upper_bound}]".

Parameters:

Name Type Description Default
keys Sequence[str] | None

Keys to convert. If a key is not defined in the dictionary it's assumed to be None.

None
formatter Callable[[dict[str, object], str], str]

Custom formatter function. It should accept a dictionary of metric result attributes and an attribute name, and return a formatted attribute value.

get_and_format_num
max_rows int | None

Maximum number of rows to convert. If None, the default value will be used. If 0 or less, all rows will be converted.

None
align Literal['auto', 'left', 'right'] | None

Column alignment mode:

  • "auto": left-align keys in default_text_keys, right-align all other keys.
  • "left": left-align all columns.
  • "right": right-align all columns.

If None, the default value will be used.

None
table_format Literal['plain', 'markdown']

Output table format:

  • "plain": plain text table.
  • "markdown": Markdown table.
'plain'

Returns:

Type Description
str

A table with results rendered as string.

Source code in src/tea_tasting/utils.py
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
def to_string(
    self,
    keys: Sequence[str] | None = None,
    formatter: Callable[[dict[str, object], str], str] = get_and_format_num,
    *,
    max_rows: int | None = None,
    align: Literal["auto", "left", "right"] | None = None,
    table_format: Literal["plain", "markdown"] = "plain",
) -> str:
    """Convert the object to a string.

    Default formatting rules:

    - If a name starts with `"rel_"` or equals to `"power"` consider it
        a percentage value. Round percentage values to 2 significant digits,
        multiply by `100` and add `"%"`.
    - Round other values to 3 significant values.
    - If value is less than `0.001` or is greater than or equal to `10_000_000`,
        format it in exponential presentation.
    - If a name ends with `"_ci"`, consider it a confidence interval.
        Look up for attributes `"{name}_lower"` and `"{name}_upper"`,
        and format the interval as `"[{lower_bound}, {upper_bound}]"`.

    Args:
        keys: Keys to convert. If a key is not defined in the dictionary
            it's assumed to be `None`.
        formatter: Custom formatter function. It should accept a dictionary
            of metric result attributes and an attribute name, and return
            a formatted attribute value.
        max_rows: Maximum number of rows to convert.
            If `None`, the default value will be used.
            If `0` or less, all rows will be converted.
        align: Column alignment mode:

            - `"auto"`: left-align keys in `default_text_keys`,
              right-align all other keys.
            - `"left"`: left-align all columns.
            - `"right"`: right-align all columns.

            If `None`, the default value will be used.
        table_format: Output table format:

            - `"plain"`: plain text table.
            - `"markdown"`: Markdown table.

    Returns:
        A table with results rendered as string.
    """
    if keys is None:
        keys = self.default_keys
    if max_rows is None:
        max_rows = self.default_max_rows
    align = (
        self.default_align
        if align is None
        else check_scalar(align, "align", typ=str, in_={"auto", "left", "right"})
    )
    table_format = check_scalar(
        table_format,
        "table_format",
        typ=str,
        in_={"plain", "markdown"},
    )

    left_aligned_keys: set[str]
    if align == "auto":
        left_aligned_keys = set(self.default_text_keys)
    elif align == "left":
        left_aligned_keys = set(keys)
    else:
        left_aligned_keys = set()

    def justify(key: str, val: str, fillchar: str = " ") -> str:
        if key in left_aligned_keys:
            return val.ljust(widths[key], fillchar)
        return val.rjust(widths[key], fillchar)

    pretty_dicts, widths, key_labels = self._to_pretty_dicts(
        keys,
        formatter,
        max_rows=max_rows,
        escape_markdown=table_format == "markdown",
    )
    if table_format == "plain":
        rows = [" ".join(justify(key, key) for key in keys).rstrip()]
        rows.extend(
            " ".join(justify(key, pretty_dict[key]) for key in keys).rstrip()
            for pretty_dict in pretty_dicts
        )
        return "\n".join(rows)

    rows = [
        f"| {' | '.join(justify(key, key_labels[key]) for key in keys)} |",
        f"| {' | '.join(justify(key, ':', '-') for key in keys)} |",
    ]
    rows.extend(
        f"| {' | '.join(justify(key, pretty_dict[key]) for key in keys)} |"
        for pretty_dict in pretty_dicts
    )
    return "\n".join(rows)

to_markdown(keys=None, formatter=get_and_format_num, *, max_rows=None, align=None) #

Convert the object to a Markdown table.

This is a convenience wrapper around to_string(table_format="markdown").

Parameters:

Name Type Description Default
keys Sequence[str] | None

Keys to convert. If a key is not defined in the dictionary it's assumed to be None.

None
formatter Callable[[dict[str, object], str], str]

Custom formatter function. It should accept a dictionary of metric result attributes and an attribute name, and return a formatted attribute value.

get_and_format_num
max_rows int | None

Maximum number of rows to convert. If None, the default value will be used. If 0 or less, all rows will be converted.

None
align Literal['auto', 'left', 'right'] | None

Column alignment mode:

  • "auto": left-align keys in default_text_keys, right-align all other keys.
  • "left": left-align all columns.
  • "right": right-align all columns.

If None, the default value will be used.

None

Returns:

Type Description
str

A table with results rendered as Markdown.

Source code in src/tea_tasting/utils.py
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
def to_markdown(
    self,
    keys: Sequence[str] | None = None,
    formatter: Callable[[dict[str, object], str], str] = get_and_format_num,
    *,
    max_rows: int | None = None,
    align: Literal["auto", "left", "right"] | None = None,
) -> str:
    """Convert the object to a Markdown table.

    This is a convenience wrapper around `to_string(table_format="markdown")`.

    Args:
        keys: Keys to convert. If a key is not defined in the dictionary
            it's assumed to be `None`.
        formatter: Custom formatter function. It should accept a dictionary
            of metric result attributes and an attribute name, and return
            a formatted attribute value.
        max_rows: Maximum number of rows to convert.
            If `None`, the default value will be used.
            If `0` or less, all rows will be converted.
        align: Column alignment mode:

            - `"auto"`: left-align keys in `default_text_keys`,
              right-align all other keys.
            - `"left"`: left-align all columns.
            - `"right"`: right-align all columns.

            If `None`, the default value will be used.

    Returns:
        A table with results rendered as Markdown.
    """
    return self.to_string(
        keys,
        formatter,
        max_rows=max_rows,
        align=align,
        table_format="markdown",
    )

to_html(keys=None, formatter=get_and_format_num, *, max_rows=None, align=None, indent=None) #

Convert the object to HTML.

Default formatting rules:

  • If a name starts with "rel_" or equals to "power" consider it a percentage value. Round percentage values to 2 significant digits, multiply by 100 and add "%".
  • Round other values to 3 significant values.
  • If value is less than 0.001 or is greater than or equal to 10_000_000, format it in exponential presentation.
  • If a name ends with "_ci", consider it a confidence interval. Look up for attributes "{name}_lower" and "{name}_upper", and format the interval as "[{lower_bound}, {upper_bound}]".

Parameters:

Name Type Description Default
keys Sequence[str] | None

Keys to convert. If a key is not defined in the dictionary it's assumed to be None.

None
formatter Callable[[dict[str, object], str], str]

Custom formatter function. It should accept a dictionary of metric result attributes and an attribute name, and return a formatted attribute value.

get_and_format_num
max_rows int | None

Maximum number of rows to convert. If None, the default value will be used. If 0 or less, all rows will be converted.

None
align Literal['auto', 'left', 'right'] | None

Column alignment mode:

  • "auto": left-align keys in default_text_keys, right-align all other keys.
  • "left": left-align all columns.
  • "right": right-align all columns.

If None, the default value will be used.

None
indent str | None

Whitespace to insert for each indentation level. If None, do not indent.

None

Returns:

Type Description
str

A table with results rendered as HTML.

Source code in src/tea_tasting/utils.py
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
def to_html(
    self,
    keys: Sequence[str] | None = None,
    formatter: Callable[[dict[str, object], str], str] = get_and_format_num,
    *,
    max_rows: int | None = None,
    align: Literal["auto", "left", "right"] | None = None,
    indent: str | None = None,
) -> str:
    """Convert the object to HTML.

    Default formatting rules:

    - If a name starts with `"rel_"` or equals to `"power"` consider it
        a percentage value. Round percentage values to 2 significant digits,
        multiply by `100` and add `"%"`.
    - Round other values to 3 significant values.
    - If value is less than `0.001` or is greater than or equal to `10_000_000`,
        format it in exponential presentation.
    - If a name ends with `"_ci"`, consider it a confidence interval.
        Look up for attributes `"{name}_lower"` and `"{name}_upper"`,
        and format the interval as `"[{lower_bound}, {upper_bound}]"`.

    Args:
        keys: Keys to convert. If a key is not defined in the dictionary
            it's assumed to be `None`.
        formatter: Custom formatter function. It should accept a dictionary
            of metric result attributes and an attribute name, and return
            a formatted attribute value.
        max_rows: Maximum number of rows to convert.
            If `None`, the default value will be used.
            If `0` or less, all rows will be converted.
        align: Column alignment mode:

            - `"auto"`: left-align keys in `default_text_keys`,
              right-align all other keys.
            - `"left"`: left-align all columns.
            - `"right"`: right-align all columns.

            If `None`, the default value will be used.
        indent: Whitespace to insert for each indentation level. If `None`,
            do not indent.

    Returns:
        A table with results rendered as HTML.
    """
    if keys is None:
        keys = self.default_keys
    if max_rows is None:
        max_rows = self.default_max_rows
    align = (
        self.default_align
        if align is None
        else check_scalar(align, "align", typ=str, in_={"auto", "left", "right"})
    )

    def get_cell_attrs(key: str) -> dict[str, str]:
        if align == "auto" and key in self.default_text_keys:
            return {"style": "text-align: left;"}
        return {}

    table = ET.Element(
        "table",
        {
            "class": "dataframe",
            "style": f"text-align: {'left' if align == 'left' else 'right'};",
        },
    )
    thead = ET.SubElement(table, "thead")
    thead_tr = ET.SubElement(thead, "tr")
    for key in keys:
        th = ET.SubElement(thead_tr, "th", get_cell_attrs(key))
        th.text = key
    tbody = ET.SubElement(table, "tbody")
    for pretty_dict in self.to_pretty_dicts(keys, formatter, max_rows=max_rows):
        tr = ET.SubElement(tbody, "tr")
        for key in keys:
            td = ET.SubElement(tr, "td", get_cell_attrs(key))
            td.text = pretty_dict[key]
    if indent is not None:
        ET.indent(table, space=indent)
    return ET.tostring(table, encoding="unicode", method="html")

with_defaults(*, keys=None, max_rows=None, align=None) #

Copies the object and sets the new default parameters.

Parameters:

Name Type Description Default
keys Sequence[str] | None

New default keys for the methods to_pretty_dicts, to_string, to_markdown, and to_html.

None
max_rows int | None

New default max_rows for the methods to_pretty_dicts, to_string, to_markdown, and to_html.

None
align Literal['auto', 'left', 'right'] | None

New default align for the methods to_string, to_markdown, and to_html.

None

Returns:

Type Description
DictsReprMixinT

A copy of the object with the new default parameters.

Source code in src/tea_tasting/utils.py
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
def with_defaults(
    self: DictsReprMixinT,
    *,
    keys: Sequence[str] | None = None,
    max_rows: int | None = None,
    align: Literal["auto", "left", "right"] | None = None,
) -> DictsReprMixinT:
    """Copies the object and sets the new default parameters.

    Args:
        keys: New default `keys` for the methods `to_pretty_dicts`, `to_string`,
            `to_markdown`, and `to_html`.
        max_rows: New default `max_rows` for the methods `to_pretty_dicts`,
            `to_string`, `to_markdown`, and `to_html`.
        align: New default `align` for the methods `to_string`, `to_markdown`,
            and `to_html`.

    Returns:
        A copy of the object with the new default parameters.
    """
    new_instance = self.__class__.__new__(self.__class__)
    new_instance.__dict__.update(self.__dict__)  # type: ignore
    new_instance._cache = None
    if keys is not None:
        new_instance.default_keys = keys
    if max_rows is not None:
        new_instance.default_max_rows = max_rows
    if align is not None:
        new_instance.default_align = check_scalar(
            align,
            "align",
            typ=str,
            in_={"auto", "left", "right"},
        )
    return new_instance

with_keys(keys) #

Copies the object and sets the new default keys.

Parameters:

Name Type Description Default
keys Sequence[str]

New default keys for the methods to_pretty_dicts, to_string, to_markdown, and to_html.

required

Returns:

Type Description
DictsReprMixinT

A copy of the object with the new default keys.

Source code in src/tea_tasting/utils.py
702
703
704
705
706
707
708
709
710
711
712
def with_keys(self: DictsReprMixinT, keys: Sequence[str]) -> DictsReprMixinT:
    """Copies the object and sets the new default `keys`.

    Args:
        keys: New default `keys` for the methods `to_pretty_dicts`, `to_string`,
            `to_markdown`, and `to_html`.

    Returns:
        A copy of the object with the new default `keys`.
    """
    return self.with_defaults(keys=keys)

with_max_rows(max_rows) #

Copies the object and sets the new default max_rows.

Parameters:

Name Type Description Default
max_rows int

New default max_rows for the methods to_pretty_dicts, to_string, to_markdown, and to_html.

required

Returns:

Type Description
DictsReprMixinT

A copy of the object with the new default max_rows.

Source code in src/tea_tasting/utils.py
715
716
717
718
719
720
721
722
723
724
725
def with_max_rows(self: DictsReprMixinT, max_rows: int) -> DictsReprMixinT:
    """Copies the object and sets the new default `max_rows`.

    Args:
        max_rows: New default `max_rows` for the methods `to_pretty_dicts`,
            `to_string`, `to_markdown`, and `to_html`.

    Returns:
        A copy of the object with the new default `max_rows`.
    """
    return self.with_defaults(max_rows=max_rows)

ReprMixin #

A mixin class that provides a method for generating a string representation.

Representation string is generated based on parameters values saved in attributes.

div(numer, denom, fill_zero_div='auto') #

Perform division, providing specified results for cases of division by zero.

Parameters:

Name Type Description Default
numer float | int

Numerator.

required
denom float | int

Denominator.

required
fill_zero_div float | int | Literal['auto']

Result if denominator is zero.

'auto'

Returns:

Type Description
float | int

Result of the division.

If fill_zero_div equals "auto", return:

  • inf if numerator is greater than 0,
  • nan if numerator is equal to or less than 0.
Source code in src/tea_tasting/utils.py
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
def div(
    numer: float | int,
    denom: float | int,
    fill_zero_div: float | int | Literal["auto"] = "auto",
) -> float |int:
    """Perform division, providing specified results for cases of division by zero.

    Args:
        numer: Numerator.
        denom: Denominator.
        fill_zero_div: Result if denominator is zero.

    Returns:
        Result of the division.

    If `fill_zero_div` equals `"auto"`, return:

    - `inf` if numerator is greater than `0`,
    - `nan` if numerator is equal to or less than `0`.
    """
    if denom != 0:
        return numer / denom
    if fill_zero_div != "auto":
        return fill_zero_div
    return float("inf") if numer > 0 else float("nan")

Float #

Bases: _NumericBase, float

Float that gracefully handles division by zero errors.

Int #

Bases: _NumericBase, int

Integer that gracefully handles division by zero errors.

numeric(value, fill_zero_div='auto') #

Convert an object to a numeric type that gracefully handles division by zero.

Parameters:

Name Type Description Default
value object

Object to convert.

required
fill_zero_div float | int | Literal['auto']

Result if denominator is zero.

'auto'

If fill_zero_div equals "auto", division by zero returns:

  • inf if numerator is greater than 0,
  • nan if numerator is equal to or less than 0.

Returns:

Type Description
Numeric

Float or integer that gracefully handles division by zero errors.

Source code in src/tea_tasting/utils.py
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
def numeric(
    value: object,
    fill_zero_div: float | int | Literal["auto"] = "auto",
) -> Numeric:
    """Convert an object to a numeric type that gracefully handles division by zero.

    Args:
        value: Object to convert.
        fill_zero_div: Result if denominator is zero.

    If `fill_zero_div` equals `"auto"`, division by zero returns:

    - `inf` if numerator is greater than `0`,
    - `nan` if numerator is equal to or less than `0`.

    Returns:
        Float or integer that gracefully handles division by zero errors.
    """
    if isinstance(value, int):
        return Int(value, fill_zero_div)
    if isinstance(value, float):
        return Float(value, fill_zero_div)
    try:
        return Int(value, fill_zero_div)
    except ValueError:
        return Float(value, fill_zero_div)