File: _converter.py

package info (click to toggle)
python-tabledata 1.3.4-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 300 kB
  • sloc: python: 1,406; makefile: 69; sh: 5
file content (36 lines) | stat: -rw-r--r-- 909 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
"""
.. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com>
"""

from collections.abc import Sequence
from typing import Any

from .error import DataError


Row = tuple[int, Any]


def to_value_matrix(headers: Sequence[str], value_matrix: Sequence[Any]) -> list[Row]:
    if not value_matrix:
        return []

    return [_to_row(headers, values, row_idx)[1] for row_idx, values in enumerate(value_matrix)]


def _to_row(headers: Sequence[str], values: Any, row_idx: int) -> Row:
    if headers:
        try:
            values = values._asdict()
        except AttributeError:
            pass

        try:
            return (row_idx, [values.get(header) for header in headers])
        except (TypeError, AttributeError):
            pass

    if not isinstance(values, (tuple, list)):
        raise DataError(f"row must be a list or tuple: actual={type(values)}")

    return (row_idx, values)