map-conform 0.1.0__py3-none-any.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.
- map_conform/__init__.py +5 -0
- map_conform/__main__.py +7 -0
- map_conform/batch/__init__.py +1 -0
- map_conform/batch/arrow.py +80 -0
- map_conform/batch/columnar.py +125 -0
- map_conform/batch/engine.py +191 -0
- map_conform/batch/files.py +207 -0
- map_conform/cli.py +460 -0
- map_conform/doctor.py +178 -0
- map_conform/errors.py +107 -0
- map_conform/expr/__init__.py +6 -0
- map_conform/expr/compiler.py +562 -0
- map_conform/expr/functions.py +542 -0
- map_conform/expr/sandbox.py +333 -0
- map_conform/expr/sdk.py +116 -0
- map_conform/map-conform-spec.schema.json +1204 -0
- map_conform/mapper.py +355 -0
- map_conform/metadata.py +73 -0
- map_conform/metrics.py +62 -0
- map_conform/naming/__init__.py +1 -0
- map_conform/naming/ascii-table.json +980 -0
- map_conform/naming/conform.py +262 -0
- map_conform/naming/flatten.py +148 -0
- map_conform/naming/nested.py +117 -0
- map_conform/naming/reserved/ansi.txt +369 -0
- map_conform/naming/reserved/duckdb.txt +114 -0
- map_conform/naming/reserved/postgres.txt +105 -0
- map_conform/naming/reserved/snowflake.txt +90 -0
- map_conform/naming/reserved.py +34 -0
- map_conform/naming/shape.py +96 -0
- map_conform/naming/streams.py +76 -0
- map_conform/naming/translit.py +170 -0
- map_conform/plan/__init__.py +1 -0
- map_conform/plan/chain.py +667 -0
- map_conform/plan/compile.py +551 -0
- map_conform/plan/lower.py +281 -0
- map_conform/plan/ops.py +336 -0
- map_conform/plan/row.py +212 -0
- map_conform/plan/vector.py +71 -0
- map_conform/rejects.py +92 -0
- map_conform/settings.py +157 -0
- map_conform/spec/__init__.py +1 -0
- map_conform/spec/_struct.py +483 -0
- map_conform/spec/bridge.py +109 -0
- map_conform/spec/check.py +380 -0
- map_conform/spec/errors.py +22 -0
- map_conform/spec/importer.py +87 -0
- map_conform/spec/jsonschema.py +54 -0
- map_conform/spec/load.py +357 -0
- map_conform/spec/model.py +473 -0
- map_conform/spec/reference.py +179 -0
- map_conform/spec/steps.py +297 -0
- map_conform/spec/stream_maps.py +233 -0
- map_conform/spec/zamboni.py +99 -0
- map_conform/transforms/__init__.py +1 -0
- map_conform/transforms/builtins.py +63 -0
- map_conform/transforms/casts.py +310 -0
- map_conform/transforms/fake.py +150 -0
- map_conform/transforms/nested.py +111 -0
- map_conform/transforms/numeric.py +318 -0
- map_conform/transforms/polars_vector.py +151 -0
- map_conform/transforms/privacy.py +220 -0
- map_conform/transforms/registry.py +116 -0
- map_conform/transforms/temporal.py +410 -0
- map_conform/transforms/text.py +249 -0
- map_conform/transforms/vector.py +386 -0
- map_conform/types/__init__.py +1 -0
- map_conform/types/canonical.py +255 -0
- map_conform/types/from_jsonschema.py +177 -0
- map_conform/types/jsontext.py +63 -0
- map_conform/types/to_arrow.py +52 -0
- map_conform/types/to_jsonschema.py +65 -0
- map_conform/types/wire.py +53 -0
- map_conform/udfs.py +327 -0
- map_conform-0.1.0.dist-info/METADATA +157 -0
- map_conform-0.1.0.dist-info/RECORD +79 -0
- map_conform-0.1.0.dist-info/WHEEL +4 -0
- map_conform-0.1.0.dist-info/entry_points.txt +2 -0
- map_conform-0.1.0.dist-info/licenses/LICENSE +201 -0
|
@@ -0,0 +1,542 @@
|
|
|
1
|
+
"""The expression function library (detailed design §7).
|
|
2
|
+
|
|
3
|
+
Every function is listed by ``map-conform functions`` with its group, signature and doc. The
|
|
4
|
+
SDK stream-map names (``md5``, ``sha256``, ``int``, ``float``, ``str``, ``bool``, ``rand``,
|
|
5
|
+
``randint``, and the ``datetime`` and ``json`` modules) behave exactly as in the SDK.
|
|
6
|
+
|
|
7
|
+
Apart from the predicates, ``coalesce`` and the Python builtins, a function given a null
|
|
8
|
+
returns null, so ``lower(x)`` on a missing ``x`` is null rather than an error.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import datetime as dt
|
|
14
|
+
import functools
|
|
15
|
+
import hashlib
|
|
16
|
+
import json
|
|
17
|
+
import random
|
|
18
|
+
import re
|
|
19
|
+
import uuid
|
|
20
|
+
from collections.abc import Callable, Mapping
|
|
21
|
+
from dataclasses import dataclass
|
|
22
|
+
from decimal import ROUND_CEILING, ROUND_FLOOR, ROUND_HALF_UP, Decimal, InvalidOperation
|
|
23
|
+
from types import MappingProxyType
|
|
24
|
+
from typing import Any
|
|
25
|
+
from zoneinfo import ZoneInfo
|
|
26
|
+
|
|
27
|
+
from map_conform.errors import StepFailed
|
|
28
|
+
from map_conform.expr.sandbox import MAX_LENGTH, MODULES, SandboxError, safe_range
|
|
29
|
+
from map_conform.transforms.temporal import TemporalCast, localize, parse_temporal
|
|
30
|
+
from map_conform.types.jsontext import dumps
|
|
31
|
+
|
|
32
|
+
_TRUE = frozenset({"true", "t", "yes", "y", "1", "on"})
|
|
33
|
+
_FALSE = frozenset({"false", "f", "no", "n", "0", "off"})
|
|
34
|
+
_UUID_NAMESPACES = MappingProxyType(
|
|
35
|
+
{
|
|
36
|
+
"dns": uuid.NAMESPACE_DNS,
|
|
37
|
+
"url": uuid.NAMESPACE_URL,
|
|
38
|
+
"oid": uuid.NAMESPACE_OID,
|
|
39
|
+
"x500": uuid.NAMESPACE_X500,
|
|
40
|
+
}
|
|
41
|
+
)
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
@dataclass(frozen=True)
|
|
45
|
+
class Function:
|
|
46
|
+
"""A function expressions may call."""
|
|
47
|
+
|
|
48
|
+
name: str
|
|
49
|
+
fn: object
|
|
50
|
+
"""The callable, or a read-only module."""
|
|
51
|
+
group: str
|
|
52
|
+
signature: str
|
|
53
|
+
doc: str
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
_LIBRARY: dict[str, Function] = {}
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def _function(group: str, signature: str, *, name: str | None = None) -> Callable[..., Any]:
|
|
60
|
+
def register(fn: Callable[..., Any]) -> Callable[..., Any]:
|
|
61
|
+
key = name or str(getattr(fn, "__name__", ""))
|
|
62
|
+
doc = (fn.__doc__ or "").strip().splitlines()[0]
|
|
63
|
+
_LIBRARY[key] = Function(key, fn, group, f"{key}({signature})", doc)
|
|
64
|
+
return fn
|
|
65
|
+
|
|
66
|
+
return register
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def _nullable(fn: Callable[..., Any]) -> Callable[..., Any]:
|
|
70
|
+
"""Return null when the first argument is null."""
|
|
71
|
+
|
|
72
|
+
@functools.wraps(fn)
|
|
73
|
+
def wrapper(value: object, *args: Any, **kwargs: Any) -> object:
|
|
74
|
+
return None if value is None else fn(value, *args, **kwargs)
|
|
75
|
+
|
|
76
|
+
return wrapper
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def _text(value: object) -> str:
|
|
80
|
+
"""A value as text: exact decimals in plain notation, temporals in ISO 8601."""
|
|
81
|
+
if isinstance(value, str):
|
|
82
|
+
return value
|
|
83
|
+
if isinstance(value, bool):
|
|
84
|
+
return "true" if value else "false"
|
|
85
|
+
if isinstance(value, Decimal):
|
|
86
|
+
return format(value, "f")
|
|
87
|
+
if isinstance(value, (dt.datetime, dt.date, dt.time)):
|
|
88
|
+
return value.isoformat()
|
|
89
|
+
return str(value)
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def _decimal(value: object) -> Decimal:
|
|
93
|
+
if isinstance(value, bool):
|
|
94
|
+
raise StepFailed("a boolean is not a number")
|
|
95
|
+
if isinstance(value, Decimal):
|
|
96
|
+
return value
|
|
97
|
+
if isinstance(value, float):
|
|
98
|
+
return Decimal(repr(value))
|
|
99
|
+
if isinstance(value, (int, str)):
|
|
100
|
+
try:
|
|
101
|
+
return Decimal(value.strip() if isinstance(value, str) else value)
|
|
102
|
+
except InvalidOperation:
|
|
103
|
+
raise StepFailed(f"{value!r} is not a number") from None
|
|
104
|
+
raise StepFailed(f"{type(value).__name__} is not a number")
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def _datetime(value: object, assume: str = "UTC") -> dt.datetime:
|
|
108
|
+
"""A value as an aware datetime: datetimes as given, ISO strings parsed, dates at midnight."""
|
|
109
|
+
parsed = value if isinstance(value, dt.date) else parse_temporal(value, TemporalCast(tz=assume))
|
|
110
|
+
if isinstance(parsed, dt.time):
|
|
111
|
+
raise StepFailed("a time of day is not a timestamp")
|
|
112
|
+
if parsed is None:
|
|
113
|
+
raise StepFailed("a timestamp is required")
|
|
114
|
+
moment = parsed if isinstance(parsed, dt.datetime) else dt.datetime.combine(parsed, dt.time())
|
|
115
|
+
return moment if moment.tzinfo else localize(moment, TemporalCast(tz=assume))
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
# --- predicates -------------------------------------------------------------------------------
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
@_function("predicates", "value")
|
|
122
|
+
def is_null(value: object) -> bool:
|
|
123
|
+
"""True for null."""
|
|
124
|
+
return value is None
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
@_function("predicates", "value")
|
|
128
|
+
def is_string(value: object) -> bool:
|
|
129
|
+
"""True for text."""
|
|
130
|
+
return isinstance(value, str)
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
@_function("predicates", "value")
|
|
134
|
+
def is_number(value: object) -> bool:
|
|
135
|
+
"""True for an int, float or decimal (not a boolean)."""
|
|
136
|
+
return isinstance(value, (int, float, Decimal)) and not isinstance(value, bool)
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
@_function("predicates", "value")
|
|
140
|
+
def is_int(value: object) -> bool:
|
|
141
|
+
"""True for an integer (not a boolean)."""
|
|
142
|
+
return isinstance(value, int) and not isinstance(value, bool)
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
@_function("predicates", "value")
|
|
146
|
+
def is_decimal(value: object) -> bool:
|
|
147
|
+
"""True for an exact decimal."""
|
|
148
|
+
return isinstance(value, Decimal)
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
@_function("predicates", "value")
|
|
152
|
+
def is_bool(value: object) -> bool:
|
|
153
|
+
"""True for a boolean."""
|
|
154
|
+
return isinstance(value, bool)
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
@_function("predicates", "value")
|
|
158
|
+
def is_datetime(value: object) -> bool:
|
|
159
|
+
"""True for a timestamp."""
|
|
160
|
+
return isinstance(value, dt.datetime)
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
@_function("predicates", "value")
|
|
164
|
+
def is_date(value: object) -> bool:
|
|
165
|
+
"""True for a date (not a timestamp)."""
|
|
166
|
+
return isinstance(value, dt.date) and not isinstance(value, dt.datetime)
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
@_function("predicates", "value")
|
|
170
|
+
def is_list(value: object) -> bool:
|
|
171
|
+
"""True for a list."""
|
|
172
|
+
return isinstance(value, (list, tuple))
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
@_function("predicates", "value")
|
|
176
|
+
def is_dict(value: object) -> bool:
|
|
177
|
+
"""True for an object."""
|
|
178
|
+
return isinstance(value, Mapping)
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
@_function("predicates", "value")
|
|
182
|
+
def is_blank(value: object) -> bool:
|
|
183
|
+
"""True for null or whitespace-only text."""
|
|
184
|
+
return value is None or (isinstance(value, str) and not value.strip())
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
@_function("predicates", "pattern, value")
|
|
188
|
+
def matches(pattern: str, value: object) -> bool:
|
|
189
|
+
"""True when the regular expression is found in the value's text; false for null."""
|
|
190
|
+
return value is not None and re.search(pattern, _text(value)) is not None
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
# --- coercion ---------------------------------------------------------------------------------
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
@_function("coercion", "value")
|
|
197
|
+
@_nullable
|
|
198
|
+
def to_int(value: object) -> int:
|
|
199
|
+
"""An integer; a fraction is an error ("12.0" is fine)."""
|
|
200
|
+
number = _decimal(value)
|
|
201
|
+
if number != number.to_integral_value():
|
|
202
|
+
raise StepFailed(f"{value!r} has a fraction")
|
|
203
|
+
return int(number)
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
@_function("coercion", "value")
|
|
207
|
+
@_nullable
|
|
208
|
+
def to_float(value: object) -> float:
|
|
209
|
+
"""A float."""
|
|
210
|
+
return float(_decimal(value))
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
@_function("coercion", "value, precision=None, scale=None")
|
|
214
|
+
@_nullable
|
|
215
|
+
def to_decimal(value: object, precision: int | None = None, scale: int | None = None) -> Decimal:
|
|
216
|
+
"""An exact decimal, rounded half up to ``scale`` digits when given."""
|
|
217
|
+
number = _decimal(value)
|
|
218
|
+
if scale is not None:
|
|
219
|
+
number = number.quantize(Decimal(1).scaleb(-scale), rounding=ROUND_HALF_UP)
|
|
220
|
+
if precision is not None and len(number.as_tuple().digits) > precision and number != 0:
|
|
221
|
+
raise StepFailed(f"{number} has more than {precision} digits")
|
|
222
|
+
return number
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
@_function("coercion", "value")
|
|
226
|
+
@_nullable
|
|
227
|
+
def to_bool(value: object) -> bool:
|
|
228
|
+
"""A boolean from true/false, yes/no, y/n, t/f, 1/0 or on/off (any case)."""
|
|
229
|
+
if isinstance(value, bool):
|
|
230
|
+
return value
|
|
231
|
+
if isinstance(value, (int, Decimal)) and value in {0, 1}:
|
|
232
|
+
return bool(value)
|
|
233
|
+
text = _text(value).strip().lower()
|
|
234
|
+
if text in _TRUE:
|
|
235
|
+
return True
|
|
236
|
+
if text in _FALSE:
|
|
237
|
+
return False
|
|
238
|
+
raise StepFailed(f"{value!r} is not a boolean")
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
@_function("coercion", "value")
|
|
242
|
+
@_nullable
|
|
243
|
+
def to_str(value: object) -> str:
|
|
244
|
+
"""Text: decimals in plain notation, temporals in ISO 8601, booleans as true/false."""
|
|
245
|
+
return _text(value)
|
|
246
|
+
|
|
247
|
+
|
|
248
|
+
@_function("coercion", "value")
|
|
249
|
+
def to_json(value: object) -> str:
|
|
250
|
+
"""JSON text (null becomes the text null)."""
|
|
251
|
+
return dumps(value)
|
|
252
|
+
|
|
253
|
+
|
|
254
|
+
@_function("coercion", "text")
|
|
255
|
+
@_nullable
|
|
256
|
+
def from_json(text: object) -> object:
|
|
257
|
+
"""The value of JSON text; fractions are exact decimals."""
|
|
258
|
+
if not isinstance(text, str):
|
|
259
|
+
return text
|
|
260
|
+
try:
|
|
261
|
+
return json.loads(text, parse_float=Decimal)
|
|
262
|
+
except json.JSONDecodeError as exc:
|
|
263
|
+
raise StepFailed(f"not JSON: {exc.msg}") from None
|
|
264
|
+
|
|
265
|
+
|
|
266
|
+
# --- temporal ---------------------------------------------------------------------------------
|
|
267
|
+
|
|
268
|
+
|
|
269
|
+
@_function("temporal", 'value, *formats, tz="UTC"')
|
|
270
|
+
@_nullable
|
|
271
|
+
def parse_datetime(value: object, *formats: str, tz: str = "UTC") -> object:
|
|
272
|
+
"""A datetime from the formats tried in order (default iso); naive results are placed in tz."""
|
|
273
|
+
options = TemporalCast(formats=formats or ("iso",), tz=tz)
|
|
274
|
+
parsed = parse_temporal(value, options)
|
|
275
|
+
if isinstance(parsed, dt.datetime) and parsed.tzinfo is None:
|
|
276
|
+
return localize(parsed, options)
|
|
277
|
+
return parsed
|
|
278
|
+
|
|
279
|
+
|
|
280
|
+
@_function("temporal", 'value, assume="UTC"')
|
|
281
|
+
@_nullable
|
|
282
|
+
def ensure_utc(value: object, assume: str = "UTC") -> dt.datetime:
|
|
283
|
+
"""A UTC datetime; naive values are taken to be in ``assume``."""
|
|
284
|
+
return _datetime(value, assume).astimezone(dt.UTC)
|
|
285
|
+
|
|
286
|
+
|
|
287
|
+
@_function("temporal", "value, tz")
|
|
288
|
+
@_nullable
|
|
289
|
+
def to_tz(value: object, tz: str) -> dt.datetime:
|
|
290
|
+
"""The same instant in another zone."""
|
|
291
|
+
return _datetime(value).astimezone(ZoneInfo(tz))
|
|
292
|
+
|
|
293
|
+
|
|
294
|
+
@_function("temporal", "")
|
|
295
|
+
def now_utc() -> dt.datetime:
|
|
296
|
+
"""The current time, in UTC."""
|
|
297
|
+
return dt.datetime.now(tz=dt.UTC)
|
|
298
|
+
|
|
299
|
+
|
|
300
|
+
_UNITS = ("year", "month", "day", "hour", "minute", "second")
|
|
301
|
+
|
|
302
|
+
|
|
303
|
+
@_function("temporal", 'value, unit="day"')
|
|
304
|
+
@_nullable
|
|
305
|
+
def date_trunc(value: object, unit: str = "day") -> object:
|
|
306
|
+
"""The value truncated to year, month, day, hour, minute or second."""
|
|
307
|
+
if unit not in _UNITS:
|
|
308
|
+
raise StepFailed(f"unit must be one of {', '.join(_UNITS)}")
|
|
309
|
+
if not isinstance(value, dt.date):
|
|
310
|
+
value = _datetime(value)
|
|
311
|
+
index = _UNITS.index(unit)
|
|
312
|
+
month = 1 if index < _UNITS.index("month") else value.month
|
|
313
|
+
day = 1 if index < _UNITS.index("day") else value.day
|
|
314
|
+
if not isinstance(value, dt.datetime): # a date
|
|
315
|
+
return value.replace(month=month, day=day)
|
|
316
|
+
return value.replace(
|
|
317
|
+
month=month,
|
|
318
|
+
day=day,
|
|
319
|
+
hour=value.hour if index >= _UNITS.index("hour") else 0,
|
|
320
|
+
minute=value.minute if index >= _UNITS.index("minute") else 0,
|
|
321
|
+
second=value.second if index >= _UNITS.index("second") else 0,
|
|
322
|
+
microsecond=0,
|
|
323
|
+
)
|
|
324
|
+
|
|
325
|
+
|
|
326
|
+
@_function("temporal", "serial, system_1904=False")
|
|
327
|
+
@_nullable
|
|
328
|
+
def excel_date(serial: object, system_1904: bool = False) -> object: # noqa: FBT001, FBT002 -- mirrors the format name
|
|
329
|
+
"""A naive datetime from a spreadsheet serial (1900 system with Lotus's leap-year bug)."""
|
|
330
|
+
fmt = "excel_serial_1904" if system_1904 else "excel_serial"
|
|
331
|
+
return parse_temporal(serial, TemporalCast(formats=(fmt,)))
|
|
332
|
+
|
|
333
|
+
|
|
334
|
+
@_function("temporal", 'number, unit="s"')
|
|
335
|
+
@_nullable
|
|
336
|
+
def from_epoch(number: object, unit: str = "s") -> object:
|
|
337
|
+
"""A UTC datetime from seconds (s), ms, us, ns since 1970, or auto by magnitude."""
|
|
338
|
+
if unit not in {"s", "ms", "us", "ns", "auto"}:
|
|
339
|
+
raise StepFailed("unit must be s, ms, us, ns or auto")
|
|
340
|
+
return parse_temporal(number, TemporalCast(formats=(f"epoch_{unit}",)))
|
|
341
|
+
|
|
342
|
+
|
|
343
|
+
# --- text -------------------------------------------------------------------------------------
|
|
344
|
+
|
|
345
|
+
|
|
346
|
+
@_function("text", "pattern, replacement, value")
|
|
347
|
+
def re_sub(pattern: str, replacement: str, value: object) -> str | None:
|
|
348
|
+
"""Replace every match of the pattern."""
|
|
349
|
+
return None if value is None else re.sub(pattern, replacement, _text(value))
|
|
350
|
+
|
|
351
|
+
|
|
352
|
+
@_function("text", "pattern, value")
|
|
353
|
+
def re_match(pattern: str, value: object) -> str | None:
|
|
354
|
+
"""The text matched at the start of the value, or null."""
|
|
355
|
+
if value is None:
|
|
356
|
+
return None
|
|
357
|
+
match = re.match(pattern, _text(value))
|
|
358
|
+
return match.group(0) if match else None
|
|
359
|
+
|
|
360
|
+
|
|
361
|
+
@_function("text", "pattern, value, group=1")
|
|
362
|
+
def re_extract(pattern: str, value: object, group: int | str = 1) -> str | None:
|
|
363
|
+
"""A group of the first match (the first group by default), or null."""
|
|
364
|
+
if value is None:
|
|
365
|
+
return None
|
|
366
|
+
match = re.search(pattern, _text(value))
|
|
367
|
+
if match is None:
|
|
368
|
+
return None
|
|
369
|
+
return match.group(group if match.re.groups else 0)
|
|
370
|
+
|
|
371
|
+
|
|
372
|
+
@_function("text", "value")
|
|
373
|
+
@_nullable
|
|
374
|
+
def lower(value: object) -> str:
|
|
375
|
+
"""Lowercase text."""
|
|
376
|
+
return _text(value).lower()
|
|
377
|
+
|
|
378
|
+
|
|
379
|
+
@_function("text", "value")
|
|
380
|
+
@_nullable
|
|
381
|
+
def upper(value: object) -> str:
|
|
382
|
+
"""Uppercase text."""
|
|
383
|
+
return _text(value).upper()
|
|
384
|
+
|
|
385
|
+
|
|
386
|
+
@_function("text", "value, chars=None")
|
|
387
|
+
@_nullable
|
|
388
|
+
def strip(value: object, chars: str | None = None) -> str:
|
|
389
|
+
"""Text without leading and trailing whitespace (or ``chars``)."""
|
|
390
|
+
return _text(value).strip(chars)
|
|
391
|
+
|
|
392
|
+
|
|
393
|
+
@_function("text", "value, sep=None, maxsplit=-1")
|
|
394
|
+
@_nullable
|
|
395
|
+
def split(value: object, sep: str | None = None, maxsplit: int = -1) -> list[str]:
|
|
396
|
+
"""A list of parts."""
|
|
397
|
+
return _text(value).split(sep, maxsplit)
|
|
398
|
+
|
|
399
|
+
|
|
400
|
+
@_function("text", 'items, sep=""')
|
|
401
|
+
@_nullable
|
|
402
|
+
def join(items: object, sep: str = "") -> str:
|
|
403
|
+
"""The items' text joined with ``sep``; null items are skipped."""
|
|
404
|
+
if not isinstance(items, (list, tuple)):
|
|
405
|
+
raise StepFailed("join needs a list")
|
|
406
|
+
return sep.join(_text(item) for item in items if item is not None)
|
|
407
|
+
|
|
408
|
+
|
|
409
|
+
@_function("text", 'value, width, char=" "')
|
|
410
|
+
@_nullable
|
|
411
|
+
def pad_left(value: object, width: int, char: str = " ") -> str:
|
|
412
|
+
"""Text padded on the left to ``width`` characters."""
|
|
413
|
+
if width > MAX_LENGTH:
|
|
414
|
+
msg = f"a width over {MAX_LENGTH} is not allowed"
|
|
415
|
+
raise SandboxError(msg)
|
|
416
|
+
return _text(value).rjust(width, char)
|
|
417
|
+
|
|
418
|
+
|
|
419
|
+
# --- numeric ----------------------------------------------------------------------------------
|
|
420
|
+
|
|
421
|
+
|
|
422
|
+
@_function("numeric", "value, ndigits=None", name="round")
|
|
423
|
+
@_nullable
|
|
424
|
+
def fn_round(value: object, ndigits: int | None = None) -> object:
|
|
425
|
+
"""Round half away from zero; an int without ndigits, else the input's type."""
|
|
426
|
+
exponent = Decimal(1).scaleb(-(ndigits or 0))
|
|
427
|
+
rounded = _decimal(value).quantize(exponent, rounding=ROUND_HALF_UP)
|
|
428
|
+
if ndigits is None:
|
|
429
|
+
return int(rounded)
|
|
430
|
+
return float(rounded) if isinstance(value, float) else rounded
|
|
431
|
+
|
|
432
|
+
|
|
433
|
+
@_function("numeric", "value")
|
|
434
|
+
@_nullable
|
|
435
|
+
def floor(value: object) -> int:
|
|
436
|
+
"""The largest integer not above the value."""
|
|
437
|
+
return int(_decimal(value).to_integral_value(rounding=ROUND_FLOOR))
|
|
438
|
+
|
|
439
|
+
|
|
440
|
+
@_function("numeric", "value")
|
|
441
|
+
@_nullable
|
|
442
|
+
def ceil(value: object) -> int:
|
|
443
|
+
"""The smallest integer not below the value."""
|
|
444
|
+
return int(_decimal(value).to_integral_value(rounding=ROUND_CEILING))
|
|
445
|
+
|
|
446
|
+
|
|
447
|
+
@_function("numeric", "value, low, high")
|
|
448
|
+
@_nullable
|
|
449
|
+
def clamp(value: Any, low: Any, high: Any) -> object: # noqa: ANN401 -- any comparable
|
|
450
|
+
"""The value limited to [low, high]."""
|
|
451
|
+
return max(low, min(high, value))
|
|
452
|
+
|
|
453
|
+
|
|
454
|
+
# --- misc -------------------------------------------------------------------------------------
|
|
455
|
+
|
|
456
|
+
|
|
457
|
+
@_function("misc", "*values")
|
|
458
|
+
def coalesce(*values: object) -> object:
|
|
459
|
+
"""The first non-null value."""
|
|
460
|
+
return next((v for v in values if v is not None), None)
|
|
461
|
+
|
|
462
|
+
|
|
463
|
+
@_function("misc", "value, other")
|
|
464
|
+
def nullif(value: object, other: object) -> object:
|
|
465
|
+
"""Null when the value equals ``other``, else the value."""
|
|
466
|
+
return None if value == other else value
|
|
467
|
+
|
|
468
|
+
|
|
469
|
+
@_function("misc", "text")
|
|
470
|
+
def md5(text: str) -> str:
|
|
471
|
+
"""The MD5 hex digest of the text (as the SDK's md5)."""
|
|
472
|
+
return hashlib.md5(text.encode(), usedforsecurity=False).hexdigest()
|
|
473
|
+
|
|
474
|
+
|
|
475
|
+
@_function("misc", "text")
|
|
476
|
+
def sha256(text: str) -> str:
|
|
477
|
+
"""The SHA-256 hex digest of the text (as the SDK's sha256)."""
|
|
478
|
+
return hashlib.sha256(text.encode()).hexdigest()
|
|
479
|
+
|
|
480
|
+
|
|
481
|
+
@_function("misc", "")
|
|
482
|
+
def uuid4() -> str:
|
|
483
|
+
"""A random UUID."""
|
|
484
|
+
return str(uuid.uuid4())
|
|
485
|
+
|
|
486
|
+
|
|
487
|
+
@_function("misc", "namespace, name")
|
|
488
|
+
def uuid5(namespace: str, name: object) -> str:
|
|
489
|
+
"""A name-based UUID; the namespace is a UUID or one of dns, url, oid, x500."""
|
|
490
|
+
space = _UUID_NAMESPACES.get(namespace) or uuid.UUID(namespace)
|
|
491
|
+
return str(uuid.uuid5(space, _text(name)))
|
|
492
|
+
|
|
493
|
+
|
|
494
|
+
@_function("misc", "")
|
|
495
|
+
def rand() -> float:
|
|
496
|
+
"""A random float in [0, 1) (as simpleeval's rand)."""
|
|
497
|
+
return random.random() # noqa: S311 -- not for security
|
|
498
|
+
|
|
499
|
+
|
|
500
|
+
@_function("misc", "top")
|
|
501
|
+
def randint(top: int) -> int:
|
|
502
|
+
"""A random integer in [0, top) (as simpleeval's randint)."""
|
|
503
|
+
return int(random.random() * top) # noqa: S311 -- not for security
|
|
504
|
+
|
|
505
|
+
|
|
506
|
+
# --- Python builtins --------------------------------------------------------------------------
|
|
507
|
+
|
|
508
|
+
_PYTHON: dict[str, tuple[Callable[..., Any], str, str]] = {
|
|
509
|
+
"int": (int, "value, base=10", "Python int (as in SDK stream maps)."),
|
|
510
|
+
"float": (float, "value", "Python float (as in SDK stream maps)."),
|
|
511
|
+
"str": (str, "value", "Python str (as in SDK stream maps)."),
|
|
512
|
+
"bool": (bool, "value", "Python truthiness (as in SDK stream maps)."),
|
|
513
|
+
"len": (len, "value", "Length of text or a list."),
|
|
514
|
+
"abs": (abs, "value", "Absolute value."),
|
|
515
|
+
"min": (min, "*values", "The smallest value."),
|
|
516
|
+
"max": (max, "*values", "The largest value."),
|
|
517
|
+
"sum": (sum, "items, start=0", "Sum of the items."),
|
|
518
|
+
"any": (any, "items", "True if any item is truthy."),
|
|
519
|
+
"all": (all, "items", "True if every item is truthy."),
|
|
520
|
+
"sorted": (sorted, "items, reverse=False", "A sorted list (no key function)."),
|
|
521
|
+
"list": (list, "items=()", "A new list."),
|
|
522
|
+
"dict": (dict, "items=(), **kwargs", "A new dict."),
|
|
523
|
+
"tuple": (tuple, "items=()", "A new tuple."),
|
|
524
|
+
"set": (set, "items=()", "A new set."),
|
|
525
|
+
"enumerate": (enumerate, "items, start=0", "(index, item) pairs."),
|
|
526
|
+
"zip": (zip, "*lists", "Tuples of items in step."),
|
|
527
|
+
"range": (safe_range, "stop | start, stop[, step]", "A range of at most 100000 integers."),
|
|
528
|
+
}
|
|
529
|
+
for _name, (_fn, _signature, _doc) in _PYTHON.items():
|
|
530
|
+
_LIBRARY[_name] = Function(_name, _fn, "python", f"{_name}({_signature})", _doc)
|
|
531
|
+
|
|
532
|
+
for _name, _proxy in MODULES.items():
|
|
533
|
+
_LIBRARY[_name] = Function(
|
|
534
|
+
_name,
|
|
535
|
+
_proxy,
|
|
536
|
+
"modules",
|
|
537
|
+
f"{_name}.<{', '.join(_proxy.names()[:6])}, ...>",
|
|
538
|
+
f"The {_name} module, read-only.",
|
|
539
|
+
)
|
|
540
|
+
|
|
541
|
+
FUNCTIONS: Mapping[str, Function] = MappingProxyType(dict(sorted(_LIBRARY.items())))
|
|
542
|
+
"""Every library function and module, by name."""
|