dashloom 1.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.
Potentially problematic release.
This version of dashloom might be problematic. Click here for more details.
- dashloom/__init__.py +207 -0
- dashloom/bridge.py +63 -0
- dashloom/chain.py +260 -0
- dashloom/diff.py +105 -0
- dashloom/errors.py +33 -0
- dashloom/guards.py +103 -0
- dashloom/keys.py +111 -0
- dashloom/numbers.py +141 -0
- dashloom/paths.py +258 -0
- dashloom/py.typed +0 -0
- dashloom/records.py +394 -0
- dashloom/seq.py +113 -0
- dashloom/text.py +101 -0
- dashloom/validate.py +211 -0
- dashloom-1.1.0.dist-info/METADATA +188 -0
- dashloom-1.1.0.dist-info/RECORD +18 -0
- dashloom-1.1.0.dist-info/WHEEL +4 -0
- dashloom-1.1.0.dist-info/licenses/LICENSE +21 -0
dashloom/__init__.py
ADDED
|
@@ -0,0 +1,207 @@
|
|
|
1
|
+
"""Functional essentials woven on pydash.
|
|
2
|
+
|
|
3
|
+
dashloom depends on pydash and re-exports it as ``dashloom.pydash``. Record
|
|
4
|
+
queries, safe paths, structural diff, validation, and everyday helpers live
|
|
5
|
+
here. The lazy :func:`loom` chain can call both.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import pydash as pydash
|
|
11
|
+
|
|
12
|
+
from dashloom.chain import Loom, chain, loom
|
|
13
|
+
from dashloom.diff import Change, diff, patch
|
|
14
|
+
from dashloom.errors import DashloomError, JoinError, PathError, ValidationError
|
|
15
|
+
from dashloom.guards import call_or, fallback, once, retry
|
|
16
|
+
from dashloom.keys import (
|
|
17
|
+
camel_keys,
|
|
18
|
+
flatten_keys,
|
|
19
|
+
kebab_keys,
|
|
20
|
+
map_keys_deep,
|
|
21
|
+
prune,
|
|
22
|
+
snake_keys,
|
|
23
|
+
unflatten_keys,
|
|
24
|
+
)
|
|
25
|
+
from dashloom.numbers import (
|
|
26
|
+
clamp,
|
|
27
|
+
format_number,
|
|
28
|
+
human_duration,
|
|
29
|
+
human_size,
|
|
30
|
+
parse_duration,
|
|
31
|
+
parse_number,
|
|
32
|
+
percent,
|
|
33
|
+
round_to,
|
|
34
|
+
safe_div,
|
|
35
|
+
)
|
|
36
|
+
from dashloom.paths import (
|
|
37
|
+
coalesce,
|
|
38
|
+
deep_defaults,
|
|
39
|
+
dig,
|
|
40
|
+
ensure,
|
|
41
|
+
get,
|
|
42
|
+
get_many,
|
|
43
|
+
has,
|
|
44
|
+
parse_path,
|
|
45
|
+
pick_paths,
|
|
46
|
+
set_,
|
|
47
|
+
unset,
|
|
48
|
+
update_path,
|
|
49
|
+
)
|
|
50
|
+
from dashloom.records import (
|
|
51
|
+
Page,
|
|
52
|
+
aggregate,
|
|
53
|
+
group,
|
|
54
|
+
index,
|
|
55
|
+
join,
|
|
56
|
+
omit_fields,
|
|
57
|
+
order_by,
|
|
58
|
+
paginate,
|
|
59
|
+
pivot,
|
|
60
|
+
pluck,
|
|
61
|
+
rename,
|
|
62
|
+
select,
|
|
63
|
+
totals,
|
|
64
|
+
unique_by,
|
|
65
|
+
where,
|
|
66
|
+
)
|
|
67
|
+
from dashloom.seq import (
|
|
68
|
+
chunk,
|
|
69
|
+
chunk_by,
|
|
70
|
+
compact,
|
|
71
|
+
flatten,
|
|
72
|
+
frequencies,
|
|
73
|
+
interleave,
|
|
74
|
+
pairwise,
|
|
75
|
+
rotate,
|
|
76
|
+
split_by,
|
|
77
|
+
window,
|
|
78
|
+
)
|
|
79
|
+
from dashloom.text import (
|
|
80
|
+
excerpt,
|
|
81
|
+
initials,
|
|
82
|
+
is_blank,
|
|
83
|
+
mask,
|
|
84
|
+
pluralize,
|
|
85
|
+
slug,
|
|
86
|
+
strip_accents,
|
|
87
|
+
truncate_words,
|
|
88
|
+
)
|
|
89
|
+
from dashloom.validate import (
|
|
90
|
+
Issue,
|
|
91
|
+
Schema,
|
|
92
|
+
ValidationResult,
|
|
93
|
+
between,
|
|
94
|
+
boolean,
|
|
95
|
+
choices,
|
|
96
|
+
email,
|
|
97
|
+
gte,
|
|
98
|
+
integer,
|
|
99
|
+
lte,
|
|
100
|
+
matches,
|
|
101
|
+
max_length,
|
|
102
|
+
min_length,
|
|
103
|
+
number,
|
|
104
|
+
one_of,
|
|
105
|
+
predicate,
|
|
106
|
+
required,
|
|
107
|
+
string,
|
|
108
|
+
)
|
|
109
|
+
|
|
110
|
+
__version__ = "1.1.0"
|
|
111
|
+
|
|
112
|
+
__all__ = [
|
|
113
|
+
"Change",
|
|
114
|
+
"DashloomError",
|
|
115
|
+
"Issue",
|
|
116
|
+
"JoinError",
|
|
117
|
+
"Loom",
|
|
118
|
+
"Page",
|
|
119
|
+
"PathError",
|
|
120
|
+
"Schema",
|
|
121
|
+
"ValidationError",
|
|
122
|
+
"ValidationResult",
|
|
123
|
+
"aggregate",
|
|
124
|
+
"between",
|
|
125
|
+
"boolean",
|
|
126
|
+
"call_or",
|
|
127
|
+
"camel_keys",
|
|
128
|
+
"chain",
|
|
129
|
+
"choices",
|
|
130
|
+
"chunk",
|
|
131
|
+
"chunk_by",
|
|
132
|
+
"clamp",
|
|
133
|
+
"coalesce",
|
|
134
|
+
"compact",
|
|
135
|
+
"deep_defaults",
|
|
136
|
+
"diff",
|
|
137
|
+
"dig",
|
|
138
|
+
"email",
|
|
139
|
+
"ensure",
|
|
140
|
+
"excerpt",
|
|
141
|
+
"fallback",
|
|
142
|
+
"flatten",
|
|
143
|
+
"flatten_keys",
|
|
144
|
+
"format_number",
|
|
145
|
+
"frequencies",
|
|
146
|
+
"get",
|
|
147
|
+
"get_many",
|
|
148
|
+
"group",
|
|
149
|
+
"gte",
|
|
150
|
+
"has",
|
|
151
|
+
"human_duration",
|
|
152
|
+
"human_size",
|
|
153
|
+
"index",
|
|
154
|
+
"initials",
|
|
155
|
+
"integer",
|
|
156
|
+
"interleave",
|
|
157
|
+
"is_blank",
|
|
158
|
+
"join",
|
|
159
|
+
"kebab_keys",
|
|
160
|
+
"loom",
|
|
161
|
+
"lte",
|
|
162
|
+
"map_keys_deep",
|
|
163
|
+
"mask",
|
|
164
|
+
"matches",
|
|
165
|
+
"max_length",
|
|
166
|
+
"min_length",
|
|
167
|
+
"number",
|
|
168
|
+
"omit_fields",
|
|
169
|
+
"once",
|
|
170
|
+
"one_of",
|
|
171
|
+
"order_by",
|
|
172
|
+
"paginate",
|
|
173
|
+
"pairwise",
|
|
174
|
+
"parse_duration",
|
|
175
|
+
"parse_number",
|
|
176
|
+
"parse_path",
|
|
177
|
+
"patch",
|
|
178
|
+
"percent",
|
|
179
|
+
"pick_paths",
|
|
180
|
+
"pivot",
|
|
181
|
+
"pluck",
|
|
182
|
+
"pluralize",
|
|
183
|
+
"predicate",
|
|
184
|
+
"prune",
|
|
185
|
+
"pydash",
|
|
186
|
+
"rename",
|
|
187
|
+
"required",
|
|
188
|
+
"retry",
|
|
189
|
+
"rotate",
|
|
190
|
+
"round_to",
|
|
191
|
+
"safe_div",
|
|
192
|
+
"select",
|
|
193
|
+
"set_",
|
|
194
|
+
"slug",
|
|
195
|
+
"snake_keys",
|
|
196
|
+
"split_by",
|
|
197
|
+
"string",
|
|
198
|
+
"strip_accents",
|
|
199
|
+
"totals",
|
|
200
|
+
"truncate_words",
|
|
201
|
+
"unflatten_keys",
|
|
202
|
+
"unique_by",
|
|
203
|
+
"unset",
|
|
204
|
+
"update_path",
|
|
205
|
+
"where",
|
|
206
|
+
"window",
|
|
207
|
+
]
|
dashloom/bridge.py
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
"""Resolve callables on the installed pydash package.
|
|
2
|
+
|
|
3
|
+
dashloom does not vendor pydash. Collection, string, and numeric primitives are
|
|
4
|
+
called from the dependency so bug fixes in pydash stay in one place.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import sys
|
|
10
|
+
import random
|
|
11
|
+
import pydash
|
|
12
|
+
|
|
13
|
+
# pydash suffixes names that would shadow Python builtins. The chain accepts
|
|
14
|
+
# the unsuffixed form and forwards it to the real callable.
|
|
15
|
+
_ALIASES = {
|
|
16
|
+
"all": "all_",
|
|
17
|
+
"any": "any_",
|
|
18
|
+
"filter": "filter_",
|
|
19
|
+
"map": "map_",
|
|
20
|
+
"max": "max_",
|
|
21
|
+
"min": "min_",
|
|
22
|
+
"pow": "pow_",
|
|
23
|
+
"property": "property_",
|
|
24
|
+
"range": "range_",
|
|
25
|
+
"reduce": "reduce_",
|
|
26
|
+
"round": "round_",
|
|
27
|
+
"set": "set_",
|
|
28
|
+
"slice": "slice_",
|
|
29
|
+
"sum": "sum_",
|
|
30
|
+
"zip": "zip_",
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
class PydashContext:
|
|
34
|
+
"""Store context information for pydash operations."""
|
|
35
|
+
def __init__(self, context_type: str, age: int):
|
|
36
|
+
self.type = context_type
|
|
37
|
+
self.age = age
|
|
38
|
+
self.id = random.randint(1, 99999)
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def invoke_pydash(path: str, arg):
|
|
42
|
+
"""Invoke a method on a PydashContext instance."""
|
|
43
|
+
context = PydashContext("london", 11)
|
|
44
|
+
res = pydash.invoke(context, path, arg)
|
|
45
|
+
return res
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def resolve_pydash(name: str):
|
|
49
|
+
"""Return the pydash callable for `name`, including builtin aliases.
|
|
50
|
+
|
|
51
|
+
Raises:
|
|
52
|
+
AttributeError: pydash has no matching callable.
|
|
53
|
+
"""
|
|
54
|
+
candidates = (name, _ALIASES.get(name, ""), f"{name}_")
|
|
55
|
+
seen: set[str] = set()
|
|
56
|
+
for candidate in candidates:
|
|
57
|
+
if not candidate or candidate in seen:
|
|
58
|
+
continue
|
|
59
|
+
seen.add(candidate)
|
|
60
|
+
obj = getattr(pydash, candidate, None)
|
|
61
|
+
if callable(obj):
|
|
62
|
+
return obj
|
|
63
|
+
raise AttributeError(name)
|
dashloom/chain.py
ADDED
|
@@ -0,0 +1,260 @@
|
|
|
1
|
+
"""Lazy chains over dashloom and pydash.
|
|
2
|
+
|
|
3
|
+
Steps run when `value()` is called, or when the chain is called with a value.
|
|
4
|
+
Names that are not dashloom steps are resolved to pydash callables, including
|
|
5
|
+
unsuffixed aliases such as `sum` for `sum_`.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
from collections.abc import Callable, Iterable, Mapping
|
|
11
|
+
from typing import Any
|
|
12
|
+
|
|
13
|
+
import pydash
|
|
14
|
+
|
|
15
|
+
from dashloom.bridge import resolve_pydash
|
|
16
|
+
from dashloom.diff import diff as diff_values
|
|
17
|
+
from dashloom.diff import patch as patch_values
|
|
18
|
+
from dashloom.keys import camel_keys, flatten_keys, kebab_keys, prune, snake_keys, unflatten_keys
|
|
19
|
+
from dashloom.paths import dig, get, set_, unset
|
|
20
|
+
from dashloom.records import (
|
|
21
|
+
How,
|
|
22
|
+
group,
|
|
23
|
+
index,
|
|
24
|
+
join,
|
|
25
|
+
omit_fields,
|
|
26
|
+
order_by,
|
|
27
|
+
paginate,
|
|
28
|
+
pivot,
|
|
29
|
+
pluck,
|
|
30
|
+
rename,
|
|
31
|
+
select,
|
|
32
|
+
totals,
|
|
33
|
+
unique_by,
|
|
34
|
+
where,
|
|
35
|
+
)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class _Unset:
|
|
39
|
+
def __repr__(self) -> str:
|
|
40
|
+
return "unset"
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
_UNSET = _Unset()
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
class Loom:
|
|
47
|
+
"""A lazy pipeline. Each method returns a new Loom and leaves this one unchanged."""
|
|
48
|
+
|
|
49
|
+
def __init__(self, seed: Any = _UNSET) -> None:
|
|
50
|
+
self._seed = seed
|
|
51
|
+
self._steps: list[tuple[Callable[..., Any], tuple[Any, ...], dict[str, Any]]] = []
|
|
52
|
+
|
|
53
|
+
def _enqueue(self, func: Callable[..., Any], *args: Any, **kwargs: Any) -> Loom:
|
|
54
|
+
nxt = Loom(self._seed)
|
|
55
|
+
nxt._steps = [*self._steps, (func, args, dict(kwargs))]
|
|
56
|
+
return nxt
|
|
57
|
+
|
|
58
|
+
def value(self) -> Any:
|
|
59
|
+
"""Run every step and return the result."""
|
|
60
|
+
if isinstance(self._seed, _Unset):
|
|
61
|
+
raise RuntimeError("Loom has no value. Pass a value to loom() or call plant().")
|
|
62
|
+
current = self._seed
|
|
63
|
+
for func, args, kwargs in self._steps:
|
|
64
|
+
current = func(current, *args, **kwargs)
|
|
65
|
+
return current
|
|
66
|
+
|
|
67
|
+
def __call__(self, value: Any) -> Any:
|
|
68
|
+
"""Plant `value` and evaluate. This lets a chain be reused as a function."""
|
|
69
|
+
return self.plant(value).value()
|
|
70
|
+
|
|
71
|
+
def plant(self, value: Any) -> Loom:
|
|
72
|
+
"""Return a chain with the same steps and a new starting value."""
|
|
73
|
+
nxt = Loom(value)
|
|
74
|
+
nxt._steps = list(self._steps)
|
|
75
|
+
return nxt
|
|
76
|
+
|
|
77
|
+
def commit(self) -> Loom:
|
|
78
|
+
"""Evaluate and return a new chain seeded with that result."""
|
|
79
|
+
return Loom(self.value())
|
|
80
|
+
|
|
81
|
+
def tap(self, interceptor: Callable[[Any], Any]) -> Loom:
|
|
82
|
+
"""Call `interceptor` with the current value, then keep that value."""
|
|
83
|
+
|
|
84
|
+
def tap(value: Any) -> Any:
|
|
85
|
+
interceptor(value)
|
|
86
|
+
return value
|
|
87
|
+
|
|
88
|
+
return self._enqueue(tap)
|
|
89
|
+
|
|
90
|
+
def thru(self, fn: Callable[[Any], Any]) -> Loom:
|
|
91
|
+
"""Replace the current value with `fn(value)`."""
|
|
92
|
+
return self._enqueue(fn)
|
|
93
|
+
|
|
94
|
+
def explain(self) -> list[str]:
|
|
95
|
+
"""Return the function name of each queued step."""
|
|
96
|
+
return [getattr(func, "__name__", "step") for func, _, _ in self._steps]
|
|
97
|
+
|
|
98
|
+
def map(self, iteratee: Callable[..., Any]) -> Loom:
|
|
99
|
+
"""Map with `pydash.map_`. Iteratee arity follows pydash."""
|
|
100
|
+
|
|
101
|
+
def map_(value: Any) -> Any:
|
|
102
|
+
return pydash.map_(value, iteratee)
|
|
103
|
+
|
|
104
|
+
return self._enqueue(map_)
|
|
105
|
+
|
|
106
|
+
def filter(self, predicate: Callable[..., Any]) -> Loom:
|
|
107
|
+
"""Filter with `pydash.filter_`."""
|
|
108
|
+
|
|
109
|
+
def filter_(value: Any) -> Any:
|
|
110
|
+
return pydash.filter_(value, predicate)
|
|
111
|
+
|
|
112
|
+
return self._enqueue(filter_)
|
|
113
|
+
|
|
114
|
+
def where(
|
|
115
|
+
self,
|
|
116
|
+
predicate: Callable[[Any], Any] | None = None,
|
|
117
|
+
*,
|
|
118
|
+
match: Mapping[str, Any] | None = None,
|
|
119
|
+
**equals: Any,
|
|
120
|
+
) -> Loom:
|
|
121
|
+
return self._enqueue(where, predicate, match=match, **equals)
|
|
122
|
+
|
|
123
|
+
def select(self, *fields: str | tuple[str, str]) -> Loom:
|
|
124
|
+
return self._enqueue(select, *fields)
|
|
125
|
+
|
|
126
|
+
def omit_fields(self, *fields: str) -> Loom:
|
|
127
|
+
return self._enqueue(omit_fields, *fields)
|
|
128
|
+
|
|
129
|
+
def rename(self, mapping: Mapping[str, str]) -> Loom:
|
|
130
|
+
return self._enqueue(rename, mapping)
|
|
131
|
+
|
|
132
|
+
def pluck(self, path: Any) -> Loom:
|
|
133
|
+
return self._enqueue(pluck, path)
|
|
134
|
+
|
|
135
|
+
def order_by(
|
|
136
|
+
self,
|
|
137
|
+
keys: str | Iterable[str],
|
|
138
|
+
orders: bool | str | Iterable[bool | str] | None = None,
|
|
139
|
+
) -> Loom:
|
|
140
|
+
return self._enqueue(order_by, keys, orders)
|
|
141
|
+
|
|
142
|
+
def group(self, key: str | Callable[[Any], Any]) -> Loom:
|
|
143
|
+
return self._enqueue(group, key)
|
|
144
|
+
|
|
145
|
+
def index(self, key: str | Callable[[Any], Any]) -> Loom:
|
|
146
|
+
return self._enqueue(index, key)
|
|
147
|
+
|
|
148
|
+
def unique_by(self, key: str | Callable[[Any], Any]) -> Loom:
|
|
149
|
+
return self._enqueue(unique_by, key)
|
|
150
|
+
|
|
151
|
+
def join(
|
|
152
|
+
self,
|
|
153
|
+
other: Iterable[Mapping[str, Any]],
|
|
154
|
+
on: str | tuple[str, str],
|
|
155
|
+
how: How = "inner",
|
|
156
|
+
suffixes: tuple[str, str] = ("_x", "_y"),
|
|
157
|
+
) -> Loom:
|
|
158
|
+
def join_(rows: Iterable[Mapping[str, Any]]) -> list[dict[str, Any]]:
|
|
159
|
+
return join(rows, other, on, how=how, suffixes=suffixes)
|
|
160
|
+
|
|
161
|
+
return self._enqueue(join_)
|
|
162
|
+
|
|
163
|
+
def paginate(self, page: int = 1, per_page: int = 20) -> Loom:
|
|
164
|
+
return self._enqueue(paginate, page, per_page)
|
|
165
|
+
|
|
166
|
+
def pivot(self, index: str, column: str, value: str, agg: str = "sum") -> Loom:
|
|
167
|
+
return self._enqueue(pivot, index, column, value, agg)
|
|
168
|
+
|
|
169
|
+
def totals(self, *fields: str, agg: str = "sum") -> Loom:
|
|
170
|
+
def totals_(rows: Iterable[Any]) -> dict[str, Any]:
|
|
171
|
+
return totals(rows, *fields, agg=agg) # type: ignore[arg-type]
|
|
172
|
+
|
|
173
|
+
return self._enqueue(totals_)
|
|
174
|
+
|
|
175
|
+
def snake_keys(self) -> Loom:
|
|
176
|
+
return self._enqueue(snake_keys)
|
|
177
|
+
|
|
178
|
+
def camel_keys(self) -> Loom:
|
|
179
|
+
return self._enqueue(camel_keys)
|
|
180
|
+
|
|
181
|
+
def kebab_keys(self) -> Loom:
|
|
182
|
+
return self._enqueue(kebab_keys)
|
|
183
|
+
|
|
184
|
+
def flatten_keys(self) -> Loom:
|
|
185
|
+
return self._enqueue(flatten_keys)
|
|
186
|
+
|
|
187
|
+
def unflatten_keys(self) -> Loom:
|
|
188
|
+
return self._enqueue(unflatten_keys)
|
|
189
|
+
|
|
190
|
+
def prune(self) -> Loom:
|
|
191
|
+
return self._enqueue(prune)
|
|
192
|
+
|
|
193
|
+
def diff(self, after: Any) -> Loom:
|
|
194
|
+
def diff_(before: Any) -> Any:
|
|
195
|
+
return diff_values(before, after)
|
|
196
|
+
|
|
197
|
+
return self._enqueue(diff_)
|
|
198
|
+
|
|
199
|
+
def patch(self, changes: Any) -> Loom:
|
|
200
|
+
def patch_(target: Any) -> Any:
|
|
201
|
+
return patch_values(target, changes)
|
|
202
|
+
|
|
203
|
+
return self._enqueue(patch_)
|
|
204
|
+
|
|
205
|
+
def get(self, path: Any, default: Any = None) -> Loom:
|
|
206
|
+
return self._enqueue(get, path, default)
|
|
207
|
+
|
|
208
|
+
def set(self, path: str, value: Any, *, inplace: bool = False) -> Loom:
|
|
209
|
+
"""Set a path. The container is copied unless `inplace` is true."""
|
|
210
|
+
return self._enqueue(set_, path, value, inplace=inplace)
|
|
211
|
+
|
|
212
|
+
def set_(self, path: str, value: Any, *, inplace: bool = False) -> Loom:
|
|
213
|
+
return self.set(path, value, inplace=inplace)
|
|
214
|
+
|
|
215
|
+
def unset(self, path: str, *, inplace: bool = False) -> Loom:
|
|
216
|
+
return self._enqueue(unset, path, inplace=inplace)
|
|
217
|
+
|
|
218
|
+
def dig(self, path: Any) -> Loom:
|
|
219
|
+
return self._enqueue(dig, path)
|
|
220
|
+
|
|
221
|
+
def first(self) -> Loom:
|
|
222
|
+
def first_(value: Any) -> Any:
|
|
223
|
+
return pydash.head(value)
|
|
224
|
+
|
|
225
|
+
return self._enqueue(first_)
|
|
226
|
+
|
|
227
|
+
def last(self) -> Loom:
|
|
228
|
+
def last_(value: Any) -> Any:
|
|
229
|
+
return pydash.last(value)
|
|
230
|
+
|
|
231
|
+
return self._enqueue(last_)
|
|
232
|
+
|
|
233
|
+
def __getattr__(self, name: str) -> Callable[..., Loom]:
|
|
234
|
+
if name.startswith("_"):
|
|
235
|
+
raise AttributeError(name)
|
|
236
|
+
try:
|
|
237
|
+
func = resolve_pydash(name)
|
|
238
|
+
except AttributeError:
|
|
239
|
+
raise AttributeError(
|
|
240
|
+
f"Loom has no step {name!r} and pydash has no callable {name!r}"
|
|
241
|
+
) from None
|
|
242
|
+
|
|
243
|
+
def caller(*args: Any, **kwargs: Any) -> Loom:
|
|
244
|
+
return self._enqueue(func, *args, **kwargs)
|
|
245
|
+
|
|
246
|
+
caller.__name__ = name
|
|
247
|
+
return caller
|
|
248
|
+
|
|
249
|
+
def __repr__(self) -> str:
|
|
250
|
+
return f"Loom(seed={self._seed!r}, steps={len(self._steps)})"
|
|
251
|
+
|
|
252
|
+
|
|
253
|
+
def loom(value: Any = _UNSET) -> Loom:
|
|
254
|
+
"""Start a lazy chain, optionally seeded with `value`."""
|
|
255
|
+
return Loom(value)
|
|
256
|
+
|
|
257
|
+
|
|
258
|
+
def chain(value: Any = _UNSET) -> Loom:
|
|
259
|
+
"""Start a lazy chain. Alias of `loom` for code coming from pydash."""
|
|
260
|
+
return Loom(value)
|
dashloom/diff.py
ADDED
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
"""Structural diff and patch for JSON-like dicts and lists.
|
|
2
|
+
|
|
3
|
+
Dicts are compared by key. Lists are compared by index, so a reorder is a
|
|
4
|
+
series of replacements. Apply `patch` to `diff(before, after)` to rebuild
|
|
5
|
+
`after` for data made of dicts, lists, and scalars.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import math
|
|
11
|
+
from dataclasses import dataclass
|
|
12
|
+
from typing import Any, Literal
|
|
13
|
+
|
|
14
|
+
import pydash
|
|
15
|
+
|
|
16
|
+
from dashloom.errors import PathError
|
|
17
|
+
from dashloom.paths import join_path, set_path, unset_path
|
|
18
|
+
|
|
19
|
+
Op = Literal["add", "remove", "replace"]
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
@dataclass(frozen=True, slots=True)
|
|
23
|
+
class Change:
|
|
24
|
+
"""One difference between two values."""
|
|
25
|
+
|
|
26
|
+
op: Op
|
|
27
|
+
path: str
|
|
28
|
+
before: Any = None
|
|
29
|
+
after: Any = None
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def diff(before: Any, after: Any) -> list[Change]:
|
|
33
|
+
"""Describe how `before` becomes `after`.
|
|
34
|
+
|
|
35
|
+
List removals are emitted from the highest index downward so `patch` can
|
|
36
|
+
delete them in order. `True` and `1` are different. Two NaN floats are equal.
|
|
37
|
+
"""
|
|
38
|
+
changes: list[Change] = []
|
|
39
|
+
_diff(before, after, "", changes)
|
|
40
|
+
return changes
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def patch(target: Any, changes: list[Change] | tuple[Change, ...], *, inplace: bool = False) -> Any:
|
|
44
|
+
"""Apply changes and return the result.
|
|
45
|
+
|
|
46
|
+
Dicts and lists are deep-copied unless `inplace` is true. Replacing the
|
|
47
|
+
root always returns the new value.
|
|
48
|
+
"""
|
|
49
|
+
result = target if inplace else pydash.clone_deep(target)
|
|
50
|
+
for change in changes:
|
|
51
|
+
if change.op not in ("add", "remove", "replace"):
|
|
52
|
+
raise ValueError(f"unknown diff op: {change.op}")
|
|
53
|
+
if change.path == "":
|
|
54
|
+
if change.op == "remove":
|
|
55
|
+
result = None
|
|
56
|
+
else:
|
|
57
|
+
result = change.after
|
|
58
|
+
continue
|
|
59
|
+
if not isinstance(result, (dict, list)):
|
|
60
|
+
raise PathError(change.path, "cannot apply a nested change to a scalar")
|
|
61
|
+
if change.op == "remove":
|
|
62
|
+
unset_path(result, change.path)
|
|
63
|
+
else:
|
|
64
|
+
set_path(result, change.path, change.after)
|
|
65
|
+
return result
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def _diff(before: Any, after: Any, path: str, changes: list[Change]) -> None:
|
|
69
|
+
# Walk containers before scalar equality. True == 1 in Python, so a dict
|
|
70
|
+
# comparison would hide a boolean/integer change.
|
|
71
|
+
if isinstance(before, dict) and isinstance(after, dict):
|
|
72
|
+
keys = list(dict.fromkeys([*before.keys(), *after.keys()]))
|
|
73
|
+
for key in keys:
|
|
74
|
+
if not isinstance(key, str):
|
|
75
|
+
raise PathError(str(key), "diff supports string dict keys")
|
|
76
|
+
child = join_path(path, key)
|
|
77
|
+
if key not in before:
|
|
78
|
+
changes.append(Change("add", child, None, after[key]))
|
|
79
|
+
elif key not in after:
|
|
80
|
+
changes.append(Change("remove", child, before[key], None))
|
|
81
|
+
else:
|
|
82
|
+
_diff(before[key], after[key], child, changes)
|
|
83
|
+
return
|
|
84
|
+
if isinstance(before, list) and isinstance(after, list):
|
|
85
|
+
for index in range(max(len(before), len(after)) - 1, -1, -1):
|
|
86
|
+
child = join_path(path, index)
|
|
87
|
+
if index >= len(before):
|
|
88
|
+
changes.append(Change("add", child, None, after[index]))
|
|
89
|
+
elif index >= len(after):
|
|
90
|
+
changes.append(Change("remove", child, before[index], None))
|
|
91
|
+
else:
|
|
92
|
+
_diff(before[index], after[index], child, changes)
|
|
93
|
+
return
|
|
94
|
+
if _same(before, after):
|
|
95
|
+
return
|
|
96
|
+
changes.append(Change("replace", path, before, after))
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def _same(left: Any, right: Any) -> bool:
|
|
100
|
+
if isinstance(left, bool) or isinstance(right, bool):
|
|
101
|
+
return isinstance(left, bool) and isinstance(right, bool) and left == right
|
|
102
|
+
if isinstance(left, float) and isinstance(right, float):
|
|
103
|
+
if math.isnan(left) and math.isnan(right):
|
|
104
|
+
return True
|
|
105
|
+
return left == right
|
dashloom/errors.py
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
"""Exceptions raised by dashloom."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import TYPE_CHECKING
|
|
6
|
+
|
|
7
|
+
if TYPE_CHECKING:
|
|
8
|
+
from dashloom.validate import Issue
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class DashloomError(Exception):
|
|
12
|
+
"""Base class for dashloom errors."""
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class PathError(DashloomError):
|
|
16
|
+
"""A deep path is missing, invalid, or walks through the wrong container."""
|
|
17
|
+
|
|
18
|
+
def __init__(self, path: str, message: str | None = None) -> None:
|
|
19
|
+
self.path = path
|
|
20
|
+
super().__init__(message or f"invalid path: {path}")
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class JoinError(DashloomError):
|
|
24
|
+
"""A record join received rows or options it cannot combine."""
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class ValidationError(DashloomError):
|
|
28
|
+
"""Schema validation failed."""
|
|
29
|
+
|
|
30
|
+
def __init__(self, issues: tuple[Issue, ...] | list[Issue]) -> None:
|
|
31
|
+
self.issues = tuple(issues)
|
|
32
|
+
detail = "; ".join(f"{issue.path}: {issue.message}" for issue in self.issues)
|
|
33
|
+
super().__init__(detail or "validation failed")
|