-
Notifications
You must be signed in to change notification settings - Fork 157
/
util.py
1684 lines (1244 loc) · 46.7 KB
/
util.py
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
TODO: This file got big. Split off pieces into the utils folder. Already split some:
- utils/text.py -- text outputs/ui related utilities and constants
- utils/python.py -- core python-related utilities
# Utilities.
## Serialization of Python objects
For deferred feedback evaluation, we need to serialize and deserialize python
functions/methods. We feature several storage classes to accomplish this:
Serializable representation | Python thing
----------------------------+------------------
Class | (python class)
Module | (python module)
Obj | (python object)
ObjSerial* | (python object)
Function | (python function)
Method | (python method)
* ObjSerial differs from Obj in that it contains the information necessary to
reconstruct the object whereas Obj does not. This information is its
constructor arguments.
"""
from __future__ import annotations
import builtins
from concurrent.futures import ThreadPoolExecutor as fThreadPoolExecutor
from enum import Enum
import importlib
import inspect
from inspect import stack
import itertools
import json
import logging
from multiprocessing.context import TimeoutError
from multiprocessing.pool import AsyncResult
from multiprocessing.pool import ThreadPool
from pathlib import Path
from pprint import PrettyPrinter
from queue import Queue
from time import sleep
from types import ModuleType
from typing import (
Any, Callable, Dict, Hashable, Iterable, List, Optional, Sequence, Set,
Tuple, TypeVar, Union
)
from merkle_json import MerkleJson
from munch import Munch as Bunch
import pandas as pd
import pydantic
from trulens_eval.keys import redact_value
from trulens_eval.utils.python import stack_with_tasks
logger = logging.getLogger(__name__)
pp = PrettyPrinter()
T = TypeVar("T")
# Optional requirements.
langchain_version = "0.0.230"
REQUIREMENT_LLAMA = (
"llama_index 0.6.24 or above is required for instrumenting llama_index apps. "
"Please install it before use: `pip install llama_index>=0.7.0`."
)
REQUIREMENT_LANGCHAIN = (
f"langchain {langchain_version} or above is required for instrumenting langchain apps. "
f"Please install it before use: `pip install langchain>={langchain_version}`."
)
class Dummy(object):
"""
Class to pretend to be a module or some other imported object. Will raise an
error if accessed in any way.
"""
def __init__(self, message: str, importer=None):
self.message = message
self.importer = importer
def __call__(self, *args, **kwargs):
raise ModuleNotFoundError(self.message)
def __getattr__(self, name):
# If in OptionalImport context, create a new dummy for the requested
# attribute. Otherwise raise error.
if self.importer is not None and self.importer.importing:
return Dummy(message=self.message, importer=self.importer)
raise ModuleNotFoundError(self.message)
class OptionalImports(object):
"""
Helper context manager for doing multiple imports from an optional module:
```python
with OptionalImports(message='Please install llama_index first'):
import llama_index
from llama_index import query_engine
```
The above python block will not raise any errors but once anything else
about llama_index or query_engine gets accessed, an error is raised with the
specified message (unless llama_index is installed of course).
"""
def __init__(self, message: str = None):
self.message = message
self.importing = False
self.imp = builtins.__import__
def __import__(self, *args, **kwargs):
try:
return self.imp(*args, **kwargs)
except ModuleNotFoundError as e:
# Check if the import error was from an import in trulens_eval as
# otherwise we don't want to intercept the error as some modules
# rely on import failures for various things.
module_name = inspect.currentframe().f_back.f_globals["__name__"]
if not module_name.startswith("trulens_eval"):
raise e
logger.debug(f"Could not import {args[0]}.")
return Dummy(message=self.message, importer=self)
def __enter__(self):
builtins.__import__ = self.__import__
self.importing = True
return self
def __exit__(self, exc_type, exc_value, exc_tb):
self.importing = False
builtins.__import__ = self.imp
if exc_value is None:
return None
print(self.message)
# Will re-raise exception unless True is returned.
return None
# Collection utilities
def first(seq: Sequence[T]) -> T:
return seq[0]
def second(seq: Sequence[T]) -> T:
return seq[1]
def third(seq: Sequence[T]) -> T:
return seq[2]
def dict_set_with(dict1: Dict, dict2: Dict):
dict1.update(dict2)
return dict1
# Generator utils
def iterable_peek(it: Iterable[T]) -> Tuple[T, Iterable[T]]:
iterator = iter(it)
item = next(iterator)
return item, itertools.chain([item], iterator)
# JSON utilities
JSON_BASES = (str, int, float, type(None))
JSON_BASES_T = Union[str, int, float, type(None)]
# JSON = (List, Dict) + JSON_BASES
# JSON_T = Union[JSON_BASES_T, List, Dict]
# TODO: rename to "JSON_LIKE" as it is not stringly json.
# JSON = Union[JSON_BASES_T, Sequence['JSON'], Dict[str, 'JSON']]
JSON = Union[JSON_BASES_T, Sequence[Any], Dict[str, Any]] # Any = JSON
# TODO: rename to "JSON".
JSON_STRICT = Dict[str, JSON]
mj = MerkleJson()
def is_empty(obj):
try:
return len(obj) == 0
except Exception:
return False
# Key for indicating non-serialized objects in json dumps.
NOSERIO = "__tru_non_serialized_object"
def is_noserio(obj):
"""
Determines whether the given json object represents some non-serializable
object. See `noserio`.
"""
return isinstance(obj, dict) and NOSERIO in obj
def noserio(obj, **extra: Dict) -> dict:
"""
Create a json structure to represent a non-serializable object. Any
additional keyword arguments are included.
"""
inner = Obj.of_object(obj).dict()
inner.update(extra)
return {NOSERIO: inner}
def obj_id_of_obj(obj: dict, prefix="obj"):
"""
Create an id from a json-able structure/definition. Should produce the same
name if definition stays the same.
"""
return f"{prefix}_hash_{mj.hash(obj)}"
def json_str_of_obj(obj: Any, *args, **kwargs) -> str:
"""
Encode the given json object as a string.
"""
if isinstance(obj, pydantic.BaseModel):
kwargs['encoder'] = json_default
return obj.json(*args, **kwargs)
return json.dumps(obj, default=json_default)
def json_default(obj: Any) -> str:
"""
Produce a representation of an object which cannot be json-serialized.
"""
# Try the encoders included with pydantic first (should handle things like
# Datetime):
try:
return pydantic.json.pydantic_encoder(obj)
except:
# Otherwise give up and indicate a non-serialization.
return noserio(obj)
# Field/key name used to indicate a circular reference in jsonified objects.
CIRCLE = "__tru_circular_reference"
# Field/key name used to indicate an exception in property retrieval (properties
# execute code in property.fget).
ERROR = "__tru_property_error"
# Key of structure where class information is stored. See WithClassInfo mixin.
CLASS_INFO = "__tru_class_info"
ALL_SPECIAL_KEYS = set([CIRCLE, ERROR, CLASS_INFO, NOSERIO])
def _safe_getattr(obj: Any, k: str) -> Any:
"""
Try to get the attribute `k` of the given object. This may evaluate some
code if the attribute is a property and may fail. In that case, an dict
indicating so is returned.
"""
v = inspect.getattr_static(obj, k)
if isinstance(v, property):
try:
v = v.fget(obj)
return v
except Exception as e:
return {ERROR: ObjSerial.of_object(e)}
else:
return v
def _clean_attributes(obj) -> Dict[str, Any]:
"""
Determine which attributes of the given object should be enumerated for
storage and/or display in UI. Returns a dict of those attributes and their
values.
For enumerating contents of objects that do not support utility classes like
pydantic, we use this method to guess what should be enumerated when
serializing/displaying.
"""
keys = dir(obj)
ret = {}
for k in keys:
if k.startswith("__"):
# These are typically very internal components not meant to be
# exposed beyond immediate definitions. Ignoring these.
continue
if k.startswith("_") and k[1:] in keys:
# Objects often have properties named `name` with their values
# coming from `_name`. Lets avoid including both the property and
# the value.
continue
v = _safe_getattr(obj, k)
ret[k] = v
return ret
# TODO: refactor to somewhere else or change instrument to a generic filter
def jsonify(
obj: Any,
dicted: Optional[Dict[int, JSON]] = None,
instrument: Optional['Instrument'] = None,
skip_specials: bool = False,
redact_keys: bool = False
) -> JSON:
"""
Convert the given object into types that can be serialized in json.
Args:
- obj: Any -- the object to jsonify.
- dicted: Optional[Dict[int, JSON]] -- the mapping from addresses of
already jsonifed objects (via id) to their json.
- instrument: Optional[Instrument] -- instrumentation functions for
checking whether to recur into components of `obj`.
- skip_specials: bool (default is False) -- if set, will remove
specially keyed structures from the json. These have keys that start
with "__tru_".
- redact_keys: bool (default is False) -- if set, will redact secrets
from the output. Secrets are detremined by `keys.py:redact_value` .
Returns:
JSON | Sequence[JSON]
"""
from trulens_eval.instruments import Instrument
instrument = instrument or Instrument()
dicted = dicted or dict()
if skip_specials:
recur_key = lambda k: k not in ALL_SPECIAL_KEYS
else:
recur_key = lambda k: True
if id(obj) in dicted:
if skip_specials:
return None
else:
return {CIRCLE: id(obj)}
if isinstance(obj, JSON_BASES):
if redact_keys and isinstance(obj, str):
return redact_value(obj)
else:
return obj
if isinstance(obj, Path):
return str(obj)
if type(obj) in pydantic.json.ENCODERS_BY_TYPE:
return obj
# TODO: should we include duplicates? If so, dicted needs to be adjusted.
new_dicted = {k: v for k, v in dicted.items()}
recur = lambda o: jsonify(
obj=o,
dicted=new_dicted,
instrument=instrument,
skip_specials=skip_specials,
redact_keys=redact_keys
)
if isinstance(obj, Enum):
return obj.name
if isinstance(obj, Dict):
temp = {}
new_dicted[id(obj)] = temp
temp.update({k: recur(v) for k, v in obj.items() if recur_key(k)})
# Redact possible secrets based on key name and value.
if redact_keys:
for k, v in temp.items():
temp[k] = redact_value(v=v, k=k)
return temp
elif isinstance(obj, Sequence):
temp = []
new_dicted[id(obj)] = temp
for x in (recur(v) for v in obj):
temp.append(x)
return temp
elif isinstance(obj, Set):
temp = []
new_dicted[id(obj)] = temp
for x in (recur(v) for v in obj):
temp.append(x)
return temp
elif isinstance(obj, pydantic.BaseModel):
# Not even trying to use pydantic.dict here.
temp = {}
new_dicted[id(obj)] = temp
temp.update(
{
k: recur(_safe_getattr(obj, k))
for k, v in obj.__fields__.items()
if not v.field_info.exclude and recur_key(k)
}
)
# Redact possible secrets based on key name and value.
if redact_keys:
for k, v in temp.items():
temp[k] = redact_value(v=v, k=k)
if instrument.to_instrument_object(obj):
temp[CLASS_INFO] = Class.of_class(
cls=obj.__class__, with_bases=True
).dict()
return temp
elif obj.__class__.__module__.startswith("llama_index."):
# Most of llama_index classes do not inherit a storage-utility class
# like pydantc so we have to enumerate their contents ourselves based on
# some heuristics.
temp = {}
new_dicted[id(obj)] = temp
kvs = _clean_attributes(obj)
temp.update(
{
k: recur(v) for k, v in kvs.items() if recur_key(k) and (
isinstance(v, JSON_BASES) or isinstance(v, Dict) or
isinstance(v, Sequence) or
instrument.to_instrument_object(v)
)
}
)
if instrument.to_instrument_object(obj):
temp[CLASS_INFO] = Class.of_class(
cls=obj.__class__, with_bases=True
).dict()
return temp
else:
logger.debug(
f"Don't know how to jsonify an object '{str(obj)[0:32]}' of type '{type(obj)}'."
)
return noserio(obj)
def leaf_queries(obj_json: JSON, query: JSONPath = None) -> Iterable[JSONPath]:
"""
Get all queries for the given object that select all of its leaf values.
"""
query = query or JSONPath()
if isinstance(obj_json, JSON_BASES):
yield query
elif isinstance(obj_json, Dict):
for k, v in obj_json.items():
sub_query = query[k]
for res in leaf_queries(obj_json[k], sub_query):
yield res
elif isinstance(obj_json, Sequence):
for i, v in enumerate(obj_json):
sub_query = query[i]
for res in leaf_queries(obj_json[i], sub_query):
yield res
else:
yield query
def all_queries(obj: Any, query: JSONPath = None) -> Iterable[JSONPath]:
"""
Get all queries for the given object.
"""
query = query or JSONPath()
if isinstance(obj, JSON_BASES):
yield query
elif isinstance(obj, pydantic.BaseModel):
yield query
for k in obj.__fields__:
v = getattr(obj, k)
sub_query = query[k]
for res in all_queries(v, sub_query):
yield res
elif isinstance(obj, Dict):
yield query
for k, v in obj.items():
sub_query = query[k]
for res in all_queries(obj[k], sub_query):
yield res
elif isinstance(obj, Sequence):
yield query
for i, v in enumerate(obj):
sub_query = query[i]
for res in all_queries(obj[i], sub_query):
yield res
else:
yield query
def all_objects(obj: Any,
query: JSONPath = None) -> Iterable[Tuple[JSONPath, Any]]:
"""
Get all queries for the given object.
"""
query = query or JSONPath()
yield (query, obj)
if isinstance(obj, JSON_BASES):
pass
elif isinstance(obj, pydantic.BaseModel):
for k in obj.__fields__:
v = getattr(obj, k)
sub_query = query[k]
for res in all_objects(v, sub_query):
yield res
elif isinstance(obj, Dict):
for k, v in obj.items():
sub_query = query[k]
for res in all_objects(obj[k], sub_query):
yield res
elif isinstance(obj, Sequence):
for i, v in enumerate(obj):
sub_query = query[i]
for res in all_objects(obj[i], sub_query):
yield res
elif isinstance(obj, Iterable):
pass
# print(f"Cannot create query for Iterable types like {obj.__class__.__name__} at query {query}. Convert the iterable to a sequence first.")
else:
pass
# print(f"Unhandled object type {obj} {type(obj)}")
def leafs(obj: Any) -> Iterable[Tuple[str, Any]]:
for q in leaf_queries(obj):
path_str = str(q)
val = q(obj)
yield (path_str, val)
def matching_objects(obj: Any,
match: Callable) -> Iterable[Tuple[JSONPath, Any]]:
for q, val in all_objects(obj):
if match(q, val):
yield (q, val)
def matching_queries(obj: Any, match: Callable) -> Iterable[JSONPath]:
for q, _ in matching_objects(obj, match=match):
yield q
class SerialModel(pydantic.BaseModel):
"""
Trulens-specific additions on top of pydantic models. Includes utilities to
help serialization mostly.
"""
@classmethod
def model_validate(cls, obj: Any, **kwargs):
if isinstance(obj, dict):
if CLASS_INFO in obj:
cls = Class(**obj[CLASS_INFO])
del obj[CLASS_INFO]
model = cls.model_validate(obj, **kwargs)
return WithClassInfo.of_model(model=model, cls=cls)
else:
print(
f"Warning: May not be able to properly reconstruct object {obj}."
)
return super().model_validate(obj, **kwargs)
def update(self, **d):
for k, v in d.items():
setattr(self, k, v)
return self
# JSONPath, a container for selector/accessors/setters of data stored in a json
# structure. Cannot make abstract since pydantic will try to initialize it.
class Step(SerialModel): #, abc.ABC):
"""
A step in a selection path.
"""
@classmethod
def __get_validator__(cls):
yield cls.validate
@classmethod
def validate(cls, d):
if not isinstance(d, Dict):
return d
ATTRIBUTE_TYPE_MAP = {
'item': GetItem,
'index': GetIndex,
'attribute': GetAttribute,
'item_or_attribute': GetItemOrAttribute,
'start': GetSlice,
'stop': GetSlice,
'step': GetSlice,
'items': GetItems,
'indices': GetIndices
}
a = next(iter(d.keys()))
if a in ATTRIBUTE_TYPE_MAP:
return ATTRIBUTE_TYPE_MAP[a](**d)
else:
raise RuntimeError(f"Don't know how to deserialize Step with {d}.")
# @abc.abstractmethod
def __call__(self, obj: Any) -> Iterable[Any]:
"""
Get the element of `obj`, indexed by `self`.
"""
raise NotImplementedError()
# @abc.abstractmethod
def set(self, obj: Any, val: Any) -> Any:
"""
Set the value(s) indicated by self in `obj` to value `val`.
"""
raise NotImplementedError()
class GetAttribute(Step):
attribute: str
def __hash__(self):
return hash(self.attribute)
def __call__(self, obj: Any) -> Iterable[Any]:
if hasattr(obj, self.attribute):
yield getattr(obj, self.attribute)
else:
raise ValueError(
f"Object {obj} does not have attribute: {self.attribute}"
)
def set(self, obj: Any, val: Any) -> Any:
if obj is None:
obj = Bunch()
if hasattr(obj, self.attribute):
setattr(obj, self.attribute, val)
return obj
else:
# might fail
setattr(obj, self.attribute, val)
return obj
def __repr__(self):
return f".{self.attribute}"
class GetIndex(Step):
index: int
def __hash__(self):
return hash(self.index)
def __call__(self, obj: Sequence[T]) -> Iterable[T]:
if isinstance(obj, Sequence):
if len(obj) > self.index:
yield obj[self.index]
else:
raise IndexError(f"Index out of bounds: {self.index}")
else:
raise ValueError(f"Object {obj} is not a sequence.")
def set(self, obj: Any, val: Any) -> Any:
if obj is None:
obj = []
assert isinstance(obj, Sequence), "Sequence expected."
if self.index >= 0:
while len(obj) <= self.index:
obj.append(None)
obj[self.index] = val
return obj
def __repr__(self):
return f"[{self.index}]"
class GetItem(Step):
item: str
def __hash__(self):
return hash(self.item)
def __call__(self, obj: Dict[str, T]) -> Iterable[T]:
if isinstance(obj, Dict):
if self.item in obj:
yield obj[self.item]
else:
raise KeyError(f"Key not in dictionary: {self.item}")
else:
raise ValueError(f"Object {obj} is not a dictionary.")
def set(self, obj: Any, val: Any) -> Any:
if obj is None:
obj = dict()
assert isinstance(obj, Dict), "Dictionary expected."
obj[self.item] = val
return obj
def __repr__(self):
return f"[{repr(self.item)}]"
class GetItemOrAttribute(Step):
# For item/attribute agnostic addressing.
item_or_attribute: str # distinct from "item" for deserialization
def __hash__(self):
return hash(self.item_or_attribute)
def __call__(self, obj: Dict[str, T]) -> Iterable[T]:
if isinstance(obj, Dict):
if self.item_or_attribute in obj:
yield obj[self.item_or_attribute]
else:
raise KeyError(
f"Key not in dictionary: {self.item_or_attribute}"
)
else:
if hasattr(obj, self.item_or_attribute):
yield getattr(obj, self.item_or_attribute)
else:
raise ValueError(
f"Object {obj} does not have item or attribute {self.item_or_attribute}."
)
def set(self, obj: Any, val: Any) -> Any:
if obj is None:
obj = dict()
if isinstance(obj, Dict):
obj[self.item_or_attribute] = val
else:
setattr(obj, self.item_or_attribute)
return obj
def __repr__(self):
return f".{self.item_or_attribute}"
class GetSlice(Step):
start: Optional[int]
stop: Optional[int]
step: Optional[int]
def __hash__(self):
return hash((self.start, self.stop, self.step))
def __call__(self, obj: Sequence[T]) -> Iterable[T]:
if isinstance(obj, Sequence):
lower, upper, step = slice(self.start, self.stop,
self.step).indices(len(obj))
for i in range(lower, upper, step):
yield obj[i]
else:
raise ValueError("Object is not a sequence.")
def set(self, obj: Any, val: Any) -> Any:
if obj is None:
obj = []
assert isinstance(obj, Sequence), "Sequence expected."
lower, upper, step = slice(self.start, self.stop,
self.step).indices(len(obj))
for i in range(lower, upper, step):
obj[i] = val
return obj
def __repr__(self):
pieces = ":".join(
[
"" if p is None else str(p)
for p in (self.start, self.stop, self.step)
]
)
if pieces == "::":
pieces = ":"
return f"[{pieces}]"
class GetIndices(Step):
indices: Sequence[int]
def __hash__(self):
return hash(tuple(self.indices))
def __call__(self, obj: Sequence[T]) -> Iterable[T]:
if isinstance(obj, Sequence):
for i in self.indices:
yield obj[i]
else:
raise ValueError("Object is not a sequence.")
def set(self, obj: Any, val: Any) -> Any:
if obj is None:
obj = []
assert isinstance(obj, Sequence), "Sequence expected."
for i in self.indices:
if i >= 0:
while len(obj) <= i:
obj.append(None)
obj[i] = val
return obj
def __repr__(self):
return f"[{','.join(map(str, self.indices))}]"
class GetItems(Step):
items: Sequence[str]
def __hash__(self):
return hash(tuple(self.items))
def __call__(self, obj: Dict[str, T]) -> Iterable[T]:
if isinstance(obj, Dict):
for i in self.items:
yield obj[i]
else:
raise ValueError("Object is not a dictionary.")
def set(self, obj: Any, val: Any) -> Any:
if obj is None:
obj = dict()
assert isinstance(obj, Dict), "Dictionary expected."
for i in self.items:
obj[i] = val
return obj
def __repr__(self):
return f"[{','.join(self.indices)}]"
class JSONPath(SerialModel):
"""
Utilitiy class for building JSONPaths.
Usage:
```python
JSONPath().record[5]['somekey]
```
"""
path: Tuple[Step, ...]
def __init__(self, path: Optional[Tuple[Step, ...]] = None):
super().__init__(path=path or ())
def __str__(self):
return "*" + ("".join(map(repr, self.path)))
def __repr__(self):
return "JSONPath()" + ("".join(map(repr, self.path)))
def __hash__(self):
return hash(self.path)
def __len__(self):
return len(self.path)
def is_immediate_prefix_of(self, other: JSONPath):
return self.is_prefix_of(other) and len(self.path) + 1 == len(
other.path
)
def is_prefix_of(self, other: JSONPath):
p = self.path
pother = other.path
if len(p) > len(pother):
return False
for s1, s2 in zip(p, pother):
if s1 != s2:
return False
return True
def set(self, obj: Any, val: Any) -> Any:
if len(self.path) == 0:
return val
first = self.path[0]
rest = JSONPath(path=self.path[1:])
try:
firsts = first(obj)
first_obj, firsts = iterable_peek(firsts)
except (ValueError, IndexError, KeyError, AttributeError):
# `first` points to an element that does not exist, use `set` to create a spot for it.
obj = first.set(obj, None) # will create a spot for `first`
firsts = first(obj)
for first_obj in firsts:
obj = first.set(
obj,
rest.set(first_obj, val),
)