cloudnet-api-client 0.12.12__tar.gz → 0.12.13__tar.gz

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.
Files changed (34) hide show
  1. {cloudnet_api_client-0.12.12 → cloudnet_api_client-0.12.13}/.github/workflows/test.yml +12 -20
  2. {cloudnet_api_client-0.12.12 → cloudnet_api_client-0.12.13}/.pre-commit-config.yaml +3 -3
  3. {cloudnet_api_client-0.12.12 → cloudnet_api_client-0.12.13}/CHANGELOG.md +5 -0
  4. {cloudnet_api_client-0.12.12 → cloudnet_api_client-0.12.13}/PKG-INFO +4 -2
  5. {cloudnet_api_client-0.12.12 → cloudnet_api_client-0.12.13}/README.md +3 -1
  6. {cloudnet_api_client-0.12.12 → cloudnet_api_client-0.12.13}/cloudnet_api_client/client.py +26 -340
  7. {cloudnet_api_client-0.12.12 → cloudnet_api_client-0.12.13}/cloudnet_api_client/dl.py +83 -29
  8. cloudnet_api_client-0.12.13/cloudnet_api_client/utils.py +439 -0
  9. {cloudnet_api_client-0.12.12 → cloudnet_api_client-0.12.13}/cloudnet_api_client/version.py +1 -1
  10. {cloudnet_api_client-0.12.12 → cloudnet_api_client-0.12.13}/pyproject.toml +2 -2
  11. {cloudnet_api_client-0.12.12 → cloudnet_api_client-0.12.13}/tests/test_client.py +78 -6
  12. cloudnet_api_client-0.12.12/cloudnet_api_client/utils.py +0 -75
  13. {cloudnet_api_client-0.12.12 → cloudnet_api_client-0.12.13}/.github/dataportal.env +0 -0
  14. {cloudnet_api_client-0.12.12 → cloudnet_api_client-0.12.13}/.github/db.env +0 -0
  15. {cloudnet_api_client-0.12.12 → cloudnet_api_client-0.12.13}/.github/docker-compose.yml +0 -0
  16. {cloudnet_api_client-0.12.12 → cloudnet_api_client-0.12.13}/.github/initdb.d/init-dbs.sh +0 -0
  17. {cloudnet_api_client-0.12.12 → cloudnet_api_client-0.12.13}/.github/ss.env +0 -0
  18. {cloudnet_api_client-0.12.12 → cloudnet_api_client-0.12.13}/.github/workflows/publish.yml +0 -0
  19. {cloudnet_api_client-0.12.12 → cloudnet_api_client-0.12.13}/.gitignore +0 -0
  20. {cloudnet_api_client-0.12.12 → cloudnet_api_client-0.12.13}/LICENSE +0 -0
  21. {cloudnet_api_client-0.12.12 → cloudnet_api_client-0.12.13}/cloudnet_api_client/__init__.py +0 -0
  22. {cloudnet_api_client-0.12.12 → cloudnet_api_client-0.12.13}/cloudnet_api_client/containers.py +0 -0
  23. {cloudnet_api_client-0.12.12 → cloudnet_api_client-0.12.13}/cloudnet_api_client/py.typed +0 -0
  24. {cloudnet_api_client-0.12.12 → cloudnet_api_client-0.12.13}/tests/data/20140205_hyytiala_classification.nc +0 -0
  25. {cloudnet_api_client-0.12.12 → cloudnet_api_client-0.12.13}/tests/data/20250711_kenttarova_l3-cf_ecmwf.nc +0 -0
  26. {cloudnet_api_client-0.12.12 → cloudnet_api_client-0.12.13}/tests/data/20250711_kenttarova_l3-cf_era5-1-12.nc +0 -0
  27. {cloudnet_api_client-0.12.12 → cloudnet_api_client-0.12.13}/tests/data/20250711_kenttarova_l3-cf_era5-7-18.nc +0 -0
  28. {cloudnet_api_client-0.12.12 → cloudnet_api_client-0.12.13}/tests/data/20250801_Magurele_CHM170137_000.nc +0 -0
  29. {cloudnet_api_client-0.12.12 → cloudnet_api_client-0.12.13}/tests/data/20250803_JOYCE_WST_01m.dat +0 -0
  30. {cloudnet_api_client-0.12.12 → cloudnet_api_client-0.12.13}/tests/data/20250808_Granada_CHM170119_0045_000.nc +0 -0
  31. {cloudnet_api_client-0.12.12 → cloudnet_api_client-0.12.13}/tests/data/20250808_hyytiala_iwc-Z-T-method.nc +0 -0
  32. {cloudnet_api_client-0.12.12 → cloudnet_api_client-0.12.13}/tests/data/20250814_bucharest_classification.nc +0 -0
  33. {cloudnet_api_client-0.12.12 → cloudnet_api_client-0.12.13}/tests/data/20250821_limassol_parsivel_41582c49.nc +0 -0
  34. {cloudnet_api_client-0.12.12 → cloudnet_api_client-0.12.13}/tests/data/20250822_leipzig-lim_ecmwf-open.nc +0 -0
@@ -2,30 +2,27 @@ name: Test and lint
2
2
 
3
3
  on: [push, pull_request]
4
4
 
5
+ concurrency:
6
+ group: ${{ github.workflow }}-${{ github.ref }}
7
+ cancel-in-progress: true
8
+
5
9
  jobs:
6
10
  test:
7
11
  timeout-minutes: 5
8
12
  strategy:
9
13
  matrix:
10
- python-version: ["3.10", "3.11", "3.12", "3.13"]
14
+ python-version: ["3.10", "3.14"]
11
15
  runs-on: ubuntu-latest
12
16
  steps:
13
- - name: Set up Python
14
- uses: actions/setup-python@v6
15
- with:
16
- python-version: ${{ matrix.python-version }}
17
-
18
17
  - name: Checkout code
19
18
  uses: actions/checkout@v6
20
19
 
21
- - name: Cache Python dependencies
22
- uses: actions/cache@v5
20
+ - name: Set up Python
21
+ uses: actions/setup-python@v6
23
22
  with:
24
- path: ~/.cache/pip
25
- key: ${{ runner.os }}-pip-${{ matrix.python-version }}-${{ hashFiles('**/pyproject.toml') }}
26
- restore-keys: |
27
- ${{ runner.os }}-pip-${{ matrix.python-version }}-
28
- ${{ runner.os }}-pip-
23
+ python-version: ${{ matrix.python-version }}
24
+ cache: pip
25
+ cache-dependency-path: pyproject.toml
29
26
 
30
27
  - name: Checkout fixtures
31
28
  uses: actions/checkout@v6
@@ -41,19 +38,14 @@ jobs:
41
38
  repository: actris-cloudnet/dataportal-fixtures
42
39
  path: dataportal-fixtures
43
40
 
44
- - name: Set up Docker Buildx
45
- uses: docker/setup-buildx-action@v4
46
-
47
41
  - name: Start dataportal
48
42
  run: docker compose -f .github/docker-compose.yml up -d --wait
49
43
 
50
44
  - name: Install dependencies
51
- run: |
52
- pip install --upgrade pip
53
- pip install .[dev,test]
45
+ run: pip install .[dev,test]
54
46
 
55
47
  - name: Run pre-commit checks
56
- if: matrix.python-version == '3.13'
48
+ if: matrix.python-version == '3.14'
57
49
  run: pre-commit run --all-files --show-diff-on-failure
58
50
 
59
51
  - name: Run tests
@@ -13,7 +13,7 @@ repos:
13
13
  args: ["--fix", "lf"]
14
14
  - id: trailing-whitespace
15
15
  - repo: https://github.com/astral-sh/ruff-pre-commit
16
- rev: v0.12.8
16
+ rev: v0.17.3
17
17
  hooks:
18
18
  - id: ruff
19
19
  args: ["--fix"]
@@ -31,10 +31,10 @@ repos:
31
31
  hooks:
32
32
  - id: prettier
33
33
  - repo: https://github.com/pappasam/toml-sort
34
- rev: v0.24.2
34
+ rev: v0.25.0
35
35
  hooks:
36
36
  - id: toml-sort-fix
37
37
  - repo: https://github.com/crate-ci/typos
38
- rev: v1.30.2
38
+ rev: v1.51.1
39
39
  hooks:
40
40
  - id: typos
@@ -5,6 +5,11 @@ All notable changes to this project will be documented in this file.
5
5
  The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
6
6
  and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
7
 
8
+ ## 0.12.13 – 2026-10-28
9
+
10
+ - Verify checksum on file download
11
+ - Test with Python 3.14
12
+
8
13
  ## 0.12.12 – 2026-09-15
9
14
 
10
15
  - Add labelling_status to Site
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: cloudnet-api-client
3
- Version: 0.12.12
3
+ Version: 0.12.13
4
4
  Summary: Cloudnet API client
5
5
  Author-email: Simo Tukiainen <simo.tukiainen@fmi.fi>
6
6
  License-File: LICENSE
@@ -64,7 +64,9 @@ file = client.file("405cc410-1f24-4ea9-bae8-da7f22be26cb")
64
64
  files = client.files(site_id="hyytiala", date="2021-01-01", product_id=["mwr", "radar"])
65
65
  file_paths = client.download(files, "data/")
66
66
 
67
- raw_files = client.raw_files(site_id="granada", date="2024-01", instrument_id="parsivel")
67
+ raw_files = client.raw_files(
68
+ site_id="granada", date="2024-01", instrument_id="parsivel"
69
+ )
68
70
  file_paths = client.download(raw_files, "data_raw/")
69
71
  ```
70
72
 
@@ -35,7 +35,9 @@ file = client.file("405cc410-1f24-4ea9-bae8-da7f22be26cb")
35
35
  files = client.files(site_id="hyytiala", date="2021-01-01", product_id=["mwr", "radar"])
36
36
  file_paths = client.download(files, "data/")
37
37
 
38
- raw_files = client.raw_files(site_id="granada", date="2024-01", instrument_id="parsivel")
38
+ raw_files = client.raw_files(
39
+ site_id="granada", date="2024-01", instrument_id="parsivel"
40
+ )
39
41
  file_paths = client.download(raw_files, "data_raw/")
40
42
  ```
41
43
 
@@ -11,18 +11,13 @@ import datetime
11
11
  import os
12
12
  import re
13
13
  import warnings
14
- from collections.abc import Iterable
15
- from dataclasses import asdict, fields, is_dataclass
14
+ from dataclasses import asdict
16
15
  from os import PathLike
17
16
  from pathlib import Path
18
- from platform import platform
19
- from typing import TypeAlias, TypeVar, cast, get_args
20
17
  from urllib.parse import urljoin
21
18
  from uuid import UUID
22
19
 
23
20
  import requests
24
- from requests.adapters import HTTPAdapter
25
- from urllib3.util.retry import Retry
26
21
 
27
22
  from cloudnet_api_client.containers import (
28
23
  PRODUCT_TYPE,
@@ -45,17 +40,27 @@ from cloudnet_api_client.containers import (
45
40
  )
46
41
  from cloudnet_api_client.dl import download_files
47
42
 
48
- from .utils import CloudnetAPIError
49
- from .version import __version__
50
-
51
- T = TypeVar("T")
52
- MetadataList = (
53
- Iterable[ProductMetadata] | Iterable[RawMetadata] | Iterable[RawModelMetadata]
43
+ from .utils import (
44
+ CloudnetAPIError,
45
+ DateParam,
46
+ DateTimeParam,
47
+ MetadataList,
48
+ QueryParam,
49
+ TMetadata,
50
+ _asdict_shallow,
51
+ _build_meta_objects,
52
+ _build_object,
53
+ _build_objects,
54
+ _build_raw_meta_objects,
55
+ _build_raw_model_meta_objects,
56
+ _check_params,
57
+ _create_instrument_object,
58
+ _create_model_object,
59
+ _make_session,
60
+ _parse_datetime,
61
+ _set_of_ids,
62
+ _validate_type,
54
63
  )
55
- TMetadata = TypeVar("TMetadata", ProductMetadata, RawMetadata, RawModelMetadata)
56
- DateParam = str | datetime.date | None
57
- DateTimeParam = str | datetime.datetime | datetime.date | None
58
- QueryParam: TypeAlias = T | Iterable[T] | None
59
64
 
60
65
 
61
66
  class APIClient:
@@ -301,12 +306,7 @@ class APIClient:
301
306
  >>> file_meta = client.file("405cc410-1f24-4ea9-bae8-da7f22be26cb")
302
307
  """
303
308
  file_res = self._get(f"files/{uuid}")[0]
304
- if file_res.get("instrument") is not None:
305
- instrument_uuid = file_res["instrument"]["uuid"]
306
- instrument_res = self._get(f"instrument-pids/{instrument_uuid}")[0]
307
- else:
308
- instrument_res = None
309
- obj = _build_meta_objects([file_res], instrument_res)[0]
309
+ obj = _build_meta_objects([file_res])[0]
310
310
  return ExtendedProductMetadata(
311
311
  **_asdict_shallow(obj),
312
312
  software=tuple(_build_objects(file_res["software"], Software)),
@@ -728,8 +728,8 @@ class APIClient:
728
728
  progress: Whether to show download progress. If None, progress will be
729
729
  shown if downloading multiple files. If True, progress will always
730
730
  be shown. If False, progress will never be shown.
731
- validate_checksum: Whether to validate file checksums after download.
732
- Defaults to False.
731
+ validate_checksum: Whether to validate file checksums or just file
732
+ sizes of existing files before download. Defaults to False.
733
733
 
734
734
  Returns:
735
735
  List of Path objects pointing to the downloaded files.
@@ -772,8 +772,8 @@ class APIClient:
772
772
  progress: Whether to show download progress. If None, progress will be
773
773
  shown if downloading multiple files. If True, progress will always
774
774
  be shown. If False, progress will never be shown.
775
- validate_checksum: Whether to validate file checksums after download.
776
- Defaults to False.
775
+ validate_checksum: Whether to validate file checksums or just file
776
+ sizes of existing files before download. Defaults to False.
777
777
 
778
778
  Returns:
779
779
  List of Path objects pointing to the downloaded files.
@@ -1055,317 +1055,3 @@ def _parse_datetime_param(
1055
1055
  return start_date, end_date - datetime.timedelta(microseconds=1)
1056
1056
  msg = f"Invalid datetime format: {dt}"
1057
1057
  raise ValueError(msg)
1058
-
1059
-
1060
- CONVERTED = {
1061
- "measurement_date",
1062
- "created_at",
1063
- "updated_at",
1064
- "size",
1065
- "uuid",
1066
- "start_time",
1067
- "stop_time",
1068
- }
1069
-
1070
-
1071
- def _build_meta_objects(
1072
- res: list[dict], instrument_meta: dict | None = None
1073
- ) -> list[ProductMetadata]:
1074
- """Build ProductMetadata objects from API response data.
1075
-
1076
- Args:
1077
- res: List of dictionaries containing product file metadata from the API.
1078
- instrument_meta: Optional dictionary containing instrument metadata to use
1079
- instead of the instrument metadata in the response.
1080
-
1081
- Returns:
1082
- List of ProductMetadata objects constructed from the response data.
1083
- """
1084
- field_names = (
1085
- {f.name for f in fields(ProductMetadata)}
1086
- - CONVERTED
1087
- - {"product", "instrument", "model", "site", "software"}
1088
- )
1089
- return [
1090
- ProductMetadata(
1091
- **{_to_snake(k): v for k, v in obj.items() if _to_snake(k) in field_names},
1092
- product=_build_object(obj["product"], Product),
1093
- instrument=_create_instrument_object(instrument_meta or obj["instrument"])
1094
- if instrument_meta or "instrument" in obj and obj["instrument"]
1095
- else None,
1096
- model=_create_model_object(obj["model"])
1097
- if "model" in obj and obj["model"]
1098
- else None,
1099
- measurement_date=datetime.date.fromisoformat(obj["measurementDate"]),
1100
- created_at=_parse_datetime(obj["createdAt"]),
1101
- updated_at=_parse_datetime(obj["updatedAt"]),
1102
- start_time=_parse_datetime(obj["startTime"]) if obj["startTime"] else None,
1103
- stop_time=_parse_datetime(obj["stopTime"]) if obj["stopTime"] else None,
1104
- size=int(obj["size"]),
1105
- uuid=UUID(obj["uuid"]),
1106
- site=_build_object(obj["site"], Site),
1107
- )
1108
- for obj in res
1109
- ]
1110
-
1111
-
1112
- def _build_raw_meta_objects(res: list[dict]) -> list[RawMetadata]:
1113
- """Build RawMetadata objects from API response data.
1114
-
1115
- Args:
1116
- res: List of dictionaries containing raw file metadata from the API.
1117
-
1118
- Returns:
1119
- List of RawMetadata objects constructed from the response data.
1120
- """
1121
- field_names = (
1122
- {f.name for f in fields(RawMetadata)}
1123
- - CONVERTED
1124
- - {"instrument", "site", "tags"}
1125
- )
1126
- return [
1127
- RawMetadata(
1128
- **{_to_snake(k): v for k, v in obj.items() if _to_snake(k) in field_names},
1129
- instrument=_create_instrument_object(obj["instrument"]),
1130
- measurement_date=datetime.date.fromisoformat(obj["measurementDate"]),
1131
- created_at=_parse_datetime(obj["createdAt"]),
1132
- updated_at=_parse_datetime(obj["updatedAt"]),
1133
- size=int(obj["size"]),
1134
- uuid=UUID(obj["uuid"]),
1135
- site=_build_object(obj["site"], Site),
1136
- tags=frozenset(obj["tags"]),
1137
- )
1138
- for obj in res
1139
- ]
1140
-
1141
-
1142
- def _build_raw_model_meta_objects(res: list[dict]) -> list[RawModelMetadata]:
1143
- """Build RawModelMetadata objects from API response data.
1144
-
1145
- Args:
1146
- res: List of dictionaries containing raw model file metadata from the API.
1147
-
1148
- Returns:
1149
- List of RawModelMetadata objects constructed from the response data.
1150
- """
1151
- field_names = (
1152
- {f.name for f in fields(RawModelMetadata)} - CONVERTED - {"model", "site"}
1153
- )
1154
- return [
1155
- RawModelMetadata(
1156
- **{_to_snake(k): v for k, v in obj.items() if _to_snake(k) in field_names},
1157
- model=_create_model_object(obj["model"]),
1158
- measurement_date=datetime.date.fromisoformat(obj["measurementDate"]),
1159
- created_at=_parse_datetime(obj["createdAt"]),
1160
- updated_at=_parse_datetime(obj["updatedAt"]),
1161
- size=int(obj["size"]),
1162
- uuid=UUID(obj["uuid"]),
1163
- site=_build_object(obj["site"], Site),
1164
- )
1165
- for obj in res
1166
- ]
1167
-
1168
-
1169
- def _create_model_object(meta: dict) -> Model:
1170
- """Create a Model object from API response data.
1171
-
1172
- Args:
1173
- meta: Dictionary containing model metadata from the API.
1174
-
1175
- Returns:
1176
- Model object constructed from the metadata.
1177
- """
1178
- return Model(
1179
- id=meta["id"],
1180
- name=meta["humanReadableName"],
1181
- optimum_order=int(meta["optimumOrder"]),
1182
- source_model_id=meta["sourceModelId"],
1183
- forecast_start=int(meta["forecastStart"])
1184
- if meta["forecastStart"] is not None
1185
- else None,
1186
- forecast_end=int(meta["forecastEnd"])
1187
- if meta["forecastEnd"] is not None
1188
- else None,
1189
- )
1190
-
1191
-
1192
- def _create_instrument_object(meta: dict) -> Instrument:
1193
- """Create an Instrument object from API response data.
1194
-
1195
- Args:
1196
- meta: Dictionary containing instrument metadata from the API.
1197
-
1198
- Returns:
1199
- Instrument object constructed from the metadata.
1200
- """
1201
- return Instrument(
1202
- instrument_id=meta.get("instrument", {}).get("id") or meta["instrumentId"],
1203
- model=meta["model"],
1204
- type=meta["type"],
1205
- uuid=UUID(meta["uuid"]),
1206
- pid=meta["pid"],
1207
- owners=tuple(meta["owners"]),
1208
- serial_number=meta["serialNumber"],
1209
- name=meta["name"],
1210
- )
1211
-
1212
-
1213
- def _build_objects(data_list: list[dict], cls: type[T]) -> list[T]:
1214
- """Build a list of dataclass objects from API response data.
1215
-
1216
- Args:
1217
- data_list: List of dictionaries containing data from the API.
1218
- cls: The dataclass type to construct objects from.
1219
-
1220
- Returns:
1221
- List of dataclass objects constructed from the data.
1222
- """
1223
- return [_build_object(d, cls) for d in data_list]
1224
-
1225
-
1226
- def _build_object(data: dict, cls: type[T]) -> T:
1227
- """Build a dataclass object from API response data.
1228
-
1229
- This function converts camelCase keys to snake_case and handles list fields
1230
- by converting them to frozensets.
1231
-
1232
- Args:
1233
- data: Dictionary containing data from the API.
1234
- cls: The dataclass type to construct an object from.
1235
-
1236
- Returns:
1237
- Dataclass object constructed from the data.
1238
- """
1239
- assert is_dataclass(cls)
1240
- field_names = {f.name for f in fields(cls)}
1241
- kwargs = {}
1242
- for k, v in data.items():
1243
- snake_key = _to_snake(k)
1244
- if snake_key in field_names:
1245
- if isinstance(v, list):
1246
- kwargs[snake_key] = frozenset(v)
1247
- else:
1248
- kwargs[snake_key] = v
1249
- object = cls(**kwargs)
1250
- return cast(T, object)
1251
-
1252
-
1253
- def _to_snake(name: str) -> str:
1254
- """Convert a camelCase or PascalCase string to snake_case.
1255
-
1256
- Args:
1257
- name: String to convert.
1258
-
1259
- Returns:
1260
- String in snake_case format.
1261
- """
1262
- return re.sub(r"(?<!^)(?=[A-Z])", "_", name).lower()
1263
-
1264
-
1265
- def _set_of_ids(res: dict, name: str) -> frozenset[str]:
1266
- """Extract a frozenset of IDs from a nested list in a dictionary.
1267
-
1268
- Args:
1269
- res: Dictionary containing a list of objects with 'id' fields.
1270
- name: Key in the dictionary where the list of objects is stored.
1271
-
1272
- Returns:
1273
- Frozenset of ID strings from the list of objects.
1274
- """
1275
- return frozenset(obj["id"] for obj in res.get(name, []))
1276
-
1277
-
1278
- def _make_session() -> requests.Session:
1279
- """Create a requests session configured for the Cloudnet API.
1280
-
1281
- The session includes a custom User-Agent header and retry strategy.
1282
-
1283
- Returns:
1284
- Configured requests.Session object.
1285
- """
1286
- session = requests.Session()
1287
- session.headers.update(
1288
- {"User-Agent": f"cloudnet-api-client/{__version__} ({platform()})"}
1289
- )
1290
- retry_strategy = Retry(total=10, backoff_factor=0.1, status_forcelist=[524])
1291
- adapter = HTTPAdapter(max_retries=retry_strategy)
1292
- session.mount("https://", adapter)
1293
- session.mount("http://", adapter)
1294
- return session
1295
-
1296
-
1297
- def _parse_datetime(dt: str) -> datetime.datetime:
1298
- """Parse a datetime string from the API into a datetime object.
1299
-
1300
- Supports datetime strings with and without microseconds.
1301
-
1302
- Args:
1303
- dt: Datetime string to parse.
1304
-
1305
- Returns:
1306
- datetime.datetime object with UTC timezone.
1307
-
1308
- Raises:
1309
- ValueError: If the datetime format is not recognized.
1310
- """
1311
- try:
1312
- return datetime.datetime.strptime(dt, "%Y-%m-%dT%H:%M:%S.%fZ").replace(
1313
- tzinfo=datetime.timezone.utc
1314
- )
1315
- except ValueError:
1316
- return datetime.datetime.strptime(dt, "%Y-%m-%dT%H:%M:%SZ").replace(
1317
- tzinfo=datetime.timezone.utc
1318
- )
1319
-
1320
-
1321
- def _check_params(params: dict, ignore: tuple = ()) -> None:
1322
- """Check that at least one parameter is set.
1323
-
1324
- Args:
1325
- params: Dictionary of parameters to check.
1326
- ignore: Tuple of parameter names to ignore in the check.
1327
-
1328
- Raises:
1329
- TypeError: If no parameters (excluding ignored ones) are set.
1330
- """
1331
- if sum(1 for key, value in params.items() if key not in ignore and value) == 0:
1332
- raise TypeError("At least one of the parameters must be set.")
1333
-
1334
-
1335
- def _asdict_shallow(obj) -> dict:
1336
- """Convert a dataclass object to a shallow dictionary.
1337
-
1338
- Args:
1339
- obj: Dataclass object to convert.
1340
-
1341
- Returns:
1342
- Dictionary mapping field names to their values.
1343
- """
1344
- return dict((field.name, getattr(obj, field.name)) for field in fields(obj))
1345
-
1346
-
1347
- def _validate_type(values, literal) -> list | None:
1348
- """Validate that values are within the allowed literal type values.
1349
-
1350
- Args:
1351
- values: Value or list of values to validate. Can be a single string or
1352
- a list of strings.
1353
- literal: A typing.Literal type containing the allowed values.
1354
-
1355
- Returns:
1356
- List of validated values, or None if values is None.
1357
-
1358
- Raises:
1359
- ValueError: If any value is not in the allowed values.
1360
- """
1361
- if values is None:
1362
- return None
1363
- if isinstance(values, str):
1364
- values = [values]
1365
- allowed_values = get_args(literal)
1366
- output = []
1367
- for value in values:
1368
- if value not in allowed_values:
1369
- raise ValueError(f"Invalid type: {value}")
1370
- output.append(value)
1371
- return output