"""
**File:** ``functions/tables.py``
**Region:** ``ds-common-placeholder-py-lib``
Description
-----------
Functions over tables and plain values, as ds-workflow-manager's builtins
behave. A table is a JSON array of objects, or a pandas ``DataFrame``. The
package does not import pandas: a frame is recognised by its interface, and
read through it without converting the whole frame.
"""
from __future__ import annotations
import json
import math
import re
from collections.abc import Hashable, Mapping
from decimal import Decimal
from typing import Any
from ..errors import ErrorCode, PlaceholderError, _Absent, _Blank
from ..grammar import BLANK
_INTEGER = re.compile(r"-?[0-9]+")
[docs]
def json_value(value: Any) -> Any:
"""*value* as plain JSON where a table library left its own types: numpy
values as Python ones (arrays as lists), a missing value (``NaN``,
``NaT``, ``pd.NA``) or an infinite number as ``None``, a timestamp as
ISO 8601, a ``Decimal`` as a number. Anything else is returned as it is,
and the caller checks that it is JSON."""
if isinstance(value, Mapping):
return {key: json_value(item) for key, item in value.items()}
if isinstance(value, list | tuple):
return [json_value(item) for item in value]
if type(value).__module__ == "numpy": # before float: np.float64 is one
return _numpy_value(value)
if value is None or isinstance(value, str | bool | int):
return value
if isinstance(value, float):
return value if math.isfinite(value) else None
if isinstance(value, Decimal):
if not value.is_finite():
return None
return int(value) if value == value.to_integral_value() else float(value)
if type(value).__name__ == "NAType": # pandas.NA
return None
try:
if value != value: # noqa: PLR0124 - true only for NaN-like values (NaT)
return None
except (TypeError, ValueError):
return value
isoformat = getattr(value, "isoformat", None)
if callable(isoformat):
return isoformat()
return value
def _numpy_value(value: Any) -> Any:
if getattr(value, "ndim", 0):
return json_value(value.tolist())
kind = getattr(getattr(value, "dtype", None), "kind", "")
if kind == "M": # datetime64: .item() of nanoseconds is an int
return None if value != value else str(value.astype("datetime64[us]").item().isoformat()) # noqa: PLR0124
if kind == "m": # timedelta64
return None if value != value else str(value) # noqa: PLR0124
return json_value(value.item())
def _is_frame(value: Any) -> bool:
"""A pandas ``DataFrame``, by its interface."""
return all(hasattr(value, name) for name in ("columns", "index", "empty", "at", "iloc")) and callable(
getattr(value, "to_dict", None)
)
def _is_rows(value: Any) -> bool:
return isinstance(value, list) and all(isinstance(row, Mapping) for row in value)
def _table(value: Any) -> Any:
"""*value*, checked to be a table.
Raises:
MissingValue: For no value (a missing argument; ``missing_value``).
PlaceholderError: ``type`` if it is not a table, ``argument`` for a
frame whose column names are not unique (as text).
"""
if value is None:
raise _Absent("no table")
if _is_frame(value):
names = [str(column) for column in value.columns]
if len(set(names)) != len(names):
raise PlaceholderError(ErrorCode.ARGUMENT, "the table's column names are not unique")
return value
if _is_rows(value):
return value
raise PlaceholderError(ErrorCode.TYPE, "not a table: expected an array of objects or a DataFrame")
def _is_empty_table(table: Any) -> bool:
return bool(table.empty) if _is_frame(table) else not table
def _column_name(name: Any) -> str:
if name is None:
raise _Absent("no column name")
if isinstance(name, int) and not isinstance(name, bool):
return str(name)
if not isinstance(name, str):
raise PlaceholderError(ErrorCode.ARGUMENT, "a column name must be a string")
return name
def _frame_column(table: Any, name: str) -> Any:
"""The frame's column label whose text is *name*."""
for column in table.columns:
if str(column) == name:
return column
raise _Blank("no such column")
def _distinct(values: list[Any]) -> list[Any]:
"""Each value once, in order. Numbers are equal by value (``1`` and
``1.0``); a boolean is not a number; arrays and objects by content."""
seen: set[Hashable] = set()
out: list[Any] = []
for value in values:
marker: Hashable
if isinstance(value, bool) or value is None or isinstance(value, str):
marker = (type(value).__name__, value)
elif isinstance(value, int):
marker = ("number", value) # exact: no float rounding of big ints
elif isinstance(value, float):
marker = ("number", int(value) if value.is_integer() else value)
else:
marker = ("json", json.dumps(value, sort_keys=True, default=str))
if marker not in seen:
seen.add(marker)
out.append(value)
return out
[docs]
def get_column_as_list(args: list[Any]) -> list[Any]:
"""The distinct values of a column, in the order they first appear (as
the manager's builtin does).
Raises:
MissingValue: For an empty table or no such column (``missing_value``;
``coalesce`` skips it).
PlaceholderError: ``type`` if the table is not one.
"""
column, table = args
name = _column_name(column)
table = _table(table)
if _is_empty_table(table):
raise _Blank("the table is empty")
if _is_frame(table):
values = json_value(table[_frame_column(table, name)].tolist())
else:
if not any(name in row for row in table):
raise _Blank("no such column")
values = [json_value(row.get(name)) for row in table]
return _distinct(values)
def _row_index(index: Any) -> int:
"""An integer row index: an int, an integral number, or its digits."""
if isinstance(index, bool):
raise PlaceholderError(ErrorCode.ARGUMENT, "index must be an integer")
if isinstance(index, int):
return index
if isinstance(index, float) and index.is_integer():
return int(index)
if isinstance(index, str) and _INTEGER.fullmatch(index.strip(BLANK)):
return int(index)
if index is None:
raise _Absent("no index")
raise PlaceholderError(ErrorCode.ARGUMENT, "index must be an integer")
[docs]
def get_value_from_dataframe(args: list[Any]) -> Any:
"""The value at row *index* and *column*. For a DataFrame the index is
its row label (as the manager's builtin reads it), for an array the
position.
Raises:
MissingValue: For an empty table, no such row or column
(``missing_value``; ``coalesce`` skips it).
PlaceholderError: ``argument`` if *index* is not an integer or the
frame's row labels are not unique or not single-level.
"""
index, column, table = args
position = _row_index(index)
name = _column_name(column)
table = _table(table)
if _is_empty_table(table):
raise _Blank("the table is empty")
if _is_frame(table):
key = _frame_column(table, name)
labels = table.index
if getattr(labels, "nlevels", 1) != 1 or not labels.is_unique:
raise PlaceholderError(ErrorCode.ARGUMENT, "the table's row labels are not unique single values")
if position not in labels:
raise _Blank("no such row")
return json_value(table.at[position, key])
if not 0 <= position < len(table):
raise _Blank("no such row")
if not any(name in row for row in table):
raise _Blank("no such column")
return json_value(table[position].get(name))
[docs]
def frame_rows(table: Any) -> list[dict[str, Any]]:
"""A DataFrame's rows as objects, column labels as text (as the other
functions address them; unique: ``_table``)."""
table = _table(table)
if _is_empty_table(table):
return []
return [{str(key): value for key, value in row.items()} for row in table.to_dict(orient="records")]
[docs]
def dataframe_to_json_array(args: list[Any]) -> str:
"""The table's rows as a JSON array, in a string: compact, non-ASCII
escaped, a missing value as ``null``. A DataFrame and an array of the
same rows give the same text.
Raises:
MissingValue: For no value (``missing_value``).
PlaceholderError: ``type`` if it is not a table, or a cell is not JSON.
"""
(table,) = args
table = _table(table)
if _is_empty_table(table):
return "[]"
rows = frame_rows(table) if _is_frame(table) else table
from ..resolve import _check_json # noqa: PLC0415
rows = json_value(rows)
_check_json(rows)
return json.dumps(rows, separators=(",", ":"))
[docs]
def json_parse(args: list[Any]) -> Any:
"""Parse a JSON text.
Raises:
MissingValue: For no value (``missing_value``).
PlaceholderError: ``type`` if the value is not a string, ``argument``
if it is not JSON.
"""
(text,) = args
if text is None:
raise _Absent("no text")
if not isinstance(text, str):
raise PlaceholderError(ErrorCode.TYPE, "json_parse takes a string")
def reject(constant: str) -> None:
raise ValueError(constant)
try:
return json.loads(text, parse_constant=reject)
except (ValueError, RecursionError):
raise PlaceholderError(ErrorCode.ARGUMENT, "the text is not valid JSON") from None
def _empty(name: str, *kinds: str) -> Any:
"""``is_empty`` and its typed variants: ``null`` or a blank string is
empty; any other value must be one of *kinds*."""
def check(args: list[Any]) -> bool:
(value,) = args
if value is None:
return True
if isinstance(value, str) and "string" in kinds:
return not value.strip(BLANK)
if "table" in kinds and (_is_frame(value) or _is_rows(value)):
return _is_empty_table(value)
if isinstance(value, list) and "array" in kinds:
return not value
if isinstance(value, Mapping) and "object" in kinds:
return not value
raise PlaceholderError(ErrorCode.TYPE, f"{name} takes {_either(kinds)}")
return check
def _either(kinds: tuple[str, ...]) -> str:
named = [f"an {kind}" if kind[0] in "aeiou" else f"a {kind}" for kind in kinds]
return named[0] if len(named) == 1 else ", ".join(named[:-1]) + ", or " + named[-1]
is_empty = _empty("is_empty", "string", "array", "object", "table")
is_string_empty = _empty("is_string_empty", "string")
is_list_empty = _empty("is_list_empty", "array")
is_dict_empty = _empty("is_dict_empty", "object")
is_dataframe_empty = _empty("is_dataframe_empty", "table")