-
Notifications
You must be signed in to change notification settings - Fork 3
/
trans.py
2740 lines (2208 loc) · 96.1 KB
/
trans.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
"""Transformation/wrapping tools"""
from functools import wraps, partial, reduce
import types
from inspect import signature, Parameter
from typing import Union, Iterable, Optional, Collection, Callable, Any
from warnings import warn
from collections.abc import Iterable
from collections.abc import (
KeysView as BaseKeysView,
ValuesView as BaseValuesView,
ItemsView as BaseItemsView,
)
from dol.errors import SetattrNotAllowed
from dol.base import Store, KvReader, AttrNames, kv_walk
from dol.util import lazyprop, num_of_args, attrs_of, wraps
from dol.signatures import Sig, KO
########################################################################################################################
# Internal Utils
def double_up_as_factory(decorator_func):
"""Repurpose a decorator both as it's original form, and as a decorator factory.
That is, from a decorator that is defined do ``wrapped_func = decorator(func, **params)``,
make it also be able to do ``wrapped_func = decorator(**params)(func)``.
Note: You'll only be able to do this if all but the first argument are keyword-only,
and the first argument (the function to decorate) has a default of ``None`` (this is for your own good).
This is validated before making the "double up as factory" decorator.
>>> @double_up_as_factory
... def decorator(func=None, *, multiplier=2):
... def _func(x):
... return func(x) * multiplier
... return _func
...
>>> def foo(x):
... return x + 1
...
>>> foo(2)
3
>>> wrapped_foo = decorator(foo, multiplier=10)
>>> wrapped_foo(2)
30
>>>
>>> multiply_by_3 = decorator(multiplier=3)
>>> wrapped_foo = multiply_by_3(foo)
>>> wrapped_foo(2)
9
>>>
>>> @decorator(multiplier=3)
... def foo(x):
... return x + 1
...
>>> foo(2)
9
Note that to be able to use double_up_as_factory, your first argument (the object to be wrapped) needs to default
to None and be the only argument that is not keyword-only (i.e. all other arguments need to be keyword only).
>>> @double_up_as_factory
... def decorator_2(func, *, multiplier=2):
... '''Should not be able to be transformed with double_up_as_factory'''
Traceback (most recent call last):
...
AssertionError: First argument of the decorator function needs to default to None. Was <class 'inspect._empty'>
>>> @double_up_as_factory
... def decorator_3(func=None, multiplier=2):
... '''Should not be able to be transformed with double_up_as_factory'''
Traceback (most recent call last):
...
AssertionError: All arguments (besides the first) need to be keyword-only
"""
def validate_decorator_func(decorator_func):
first_param, *other_params = signature(decorator_func).parameters.values()
assert first_param.default is None, (
f'First argument of the decorator function needs to default to None. '
f'Was {first_param.default}'
)
assert all(
p.kind in {p.KEYWORD_ONLY, p.VAR_KEYWORD} for p in other_params
), f'All arguments (besides the first) need to be keyword-only'
return True
validate_decorator_func(decorator_func)
@wraps(decorator_func)
def _double_up_as_factory(wrapped=None, **kwargs):
if wrapped is None: # then we want a factory
return partial(decorator_func, **kwargs)
else:
return decorator_func(wrapped, **kwargs)
return _double_up_as_factory
def _all_but_first_arg_are_keyword_only(func):
"""
>>> def foo(a, *, b, c=2): ...
>>> _all_but_first_arg_are_keyword_only(foo)
True
>>> def bar(a, b, *, c=2): ...
>>> _all_but_first_arg_are_keyword_only(bar)
False
"""
kinds = (p.kind for p in signature(func).parameters.values())
_ = next(kinds) # consume first item, and all remaining should be KEYWORD_ONLY
return all(kind == Parameter.KEYWORD_ONLY for kind in kinds)
# TODO: Separate the wrapper_assignments injection (and possibly make these not show up at the interface?)
# FIXME: doctest line numbers not shown correctly when wrapped by store_decorator!
def store_decorator(func):
"""Helper to make store decorators.
You provide a class-decorating function ``func`` that takes a store type (and possibly additional params)
and returns another decorated store type.
``store_decorator`` takes that ``func`` and provides an enhanced class decorator specialized for stores.
Namely it will:
- Add ``__module__``, ``__qualname__``, ``__name__`` and ``__doc__`` arguments to it
- Copy the aforementioned arguments to the decorated class, or copy the attributes of the original if not specified.
- Output a decorator that can be used in four different ways: a class/instance decorator/factory.
By class/instance decorator/factory we mean that if ``A`` is a class, ``a`` an instance of it,
and ``deco`` a decorator obtained with ``store_decorator(func)``,
we can use ``deco`` to
- class decorator: decorate a class
- class decorator factory: make a function that decorates classes
- instance decorator: decorate an instance of a store
- instancce decorator factor: make a function that decorates instances of stores
For example, say we have the following ``deco`` that we made with ``store_decorator``:
>>> @store_decorator
... def deco(cls=None, *, x=1):
... # do stuff to cls, or a copy of it...
... cls.x = x # like this for example
... return cls
And a class that has nothing to it:
>>> class A: ...
Nammely, it doesn't have an ``x``
>>> hasattr(A, 'x')
False
We make a ``decorated_A`` with ``deco`` (class decorator example)
>>> t = deco(A, x=42)
>>> assert isinstance(t, type)
and we see that we now have an ``x`` and it's 42
>>> hasattr(A, 'x')
True
>>> A.x
42
But we could have also made a factory to decorate ``A`` and anything else that comes our way.
>>> paint_it_42 = deco(x=42)
>>> decorated_A = paint_it_42(A)
>>> assert decorated_A.x == 42
>>> class B:
... x = 'destined to disappear'
>>> assert paint_it_42(B).x == 42
To be fair though, you'll probably see the factory usage appear in the following form,
where the class is decorated at definition time.
>>> @deco(x=42)
... class B:
... pass
>>> assert B.x == 42
If your exists already, and you want to keep it as is (with the same name), you can
use subclassing to transform a copy of ``A`` instead, as below.
Also note in the following example, that ``deco`` was used without parentheses,
which is equivalent to ``@deco()``,
and yes, store_decorator makes that possible to, as long as your params have defaults
>>> @deco
... class decorated_A(A):
... pass
>>> assert decorated_A.x == 1
>>> assert A.x == 42
Finally, you can also decorate instances:
>>> class A: ...
>>> a = A()
>>> hasattr(a, 'x')
False
>>> b = deco(a); assert b.x == 1; # b has an x and it's 1
>>> b = deco()(a); assert b.x == 1; # b has an x and it's 1
>>> b = deco(a, x=42); assert b.x == 42 # b has an x and it's 42
>>> b = deco(x=42)(a); assert b.x == 42; # b has an x and it's 42
WARNING: Note though that the type of ``b`` is not the same type as ``a``
>>> isinstance(b, a.__class__)
False
No, ``b`` is an instance of a ``dol.base.Store``, which is a class containing an
instance of a store (here, ``a``).
>>> type(b)
<class 'dol.base.Store'>
>>> b.store == a
True
Now, here's some more example, slightly closer to real usage
>>> from dol.trans import store_decorator
>>> from inspect import signature
>>>
>>> def rm_deletion(store=None, *, msg='Deletions not allowed.'):
... name = getattr(store, '__name__', 'Something') + '_w_sommething'
... assert isinstance(store, type), f"Should be a type, was {type(store)}: {store}"
... wrapped_store = type(name, (store,), {})
... wrapped_store.__delitem__ = lambda self, k: msg
... return wrapped_store
...
>>> remove_deletion = store_decorator(rm_deletion)
See how the signature of the wrapper has some extra inputs that were injected (__module__, __qualname__, etc.):
>>> print(str(signature(remove_deletion)))
(store=None, *, msg='Deletions not allowed.', __module__=None, __name__=None, __qualname__=None, __doc__=None, __annotations__=None, __defaults__=None, __kwdefaults__=None)
Using it as a class decorator factory (the most common way):
As a class decorator "factory", without parameters (and without ()):
>>> from collections import UserDict
>>> @remove_deletion
... class WD(UserDict):
... "Here's the doc"
... pass
>>> wd = WD(x=5, y=7)
>>> assert wd == UserDict(x=5, y=7) # same as far as dict comparison goes
>>> assert wd.__delitem__('x') == 'Deletions not allowed.'
>>> assert wd.__doc__ == "Here's the doc"
As a class decorator "factory", with parameters:
>>> @remove_deletion(msg='No way. I do not trust you!!')
... class WD(UserDict): ...
>>> wd = WD(x=5, y=7)
>>> assert wd == UserDict(x=5, y=7) # same as far as dict comparison goes
>>> assert wd.__delitem__('x') == 'No way. I do not trust you!!'
The __doc__ is empty:
>>> assert WD.__doc__ == None
But we could specify a doc if we wanted to:
>>> @remove_deletion(__doc__="Hi, I'm a doc.")
... class WD(UserDict):
... "This is the original doc, that will be overritten"
>>> assert WD.__doc__ == "Hi, I'm a doc."
The class decorations above are equivalent to the two following:
>>> WD = remove_deletion(UserDict)
>>> wd = WD(x=5, y=7)
>>> assert wd == UserDict(x=5, y=7) # same as far as dict comparison goes
>>> assert wd.__delitem__('x') == 'Deletions not allowed.'
>>>
>>> WD = remove_deletion(UserDict, msg='No way. I do not trust you!!')
>>> wd = WD(x=5, y=7)
>>> assert wd == UserDict(x=5, y=7) # same as far as dict comparison goes
>>> assert wd.__delitem__('x') == 'No way. I do not trust you!!'
But we can also decorate instances. In this case they will be wrapped in a Store class
before being passed on to the actual decorator.
>>> d = UserDict(x=5, y=7)
>>> wd = remove_deletion(d)
>>> assert wd == d # same as far as dict comparison goes
>>> assert wd.__delitem__('x') == 'Deletions not allowed.'
>>>
>>> d = UserDict(x=5, y=7)
>>> wd = remove_deletion(d, msg='No way. I do not trust you!!')
>>> assert wd == d # same as far as dict comparison goes
>>> assert wd.__delitem__('x') == 'No way. I do not trust you!!'
"""
# wrapper_assignments = ('__module__', '__qualname__', '__name__', '__doc__', '__annotations__')
wrapper_assignments = (
'__module__',
'__name__',
'__qualname__',
'__doc__',
'__annotations__',
'__defaults__',
'__kwdefaults__',
)
@wraps(func)
def _func_wrapping_store_in_cls_if_not_type(store, **kwargs):
specials = dict()
for a in wrapper_assignments:
v = kwargs.pop(a, getattr(store, a, None))
if v is not None:
specials[a] = v
if not isinstance(store, type):
store_instance = store
# StoreWrap = type(
# 'StoreWrap', (Store,), {}
# ) # a copy of Store, so Store isn't transformed directly
WrapperStore = func(Store, **kwargs)
r = WrapperStore(store_instance)
else:
assert _all_but_first_arg_are_keyword_only(func), (
"To use decorating_store_cls, all but the first of your function's arguments need to be all keyword only. "
f'The signature was {func.__qualname__}{signature(func)}'
)
r = func(store, **kwargs)
for k, v in specials.items():
if v is not None:
setattr(r, k, v)
return r
_func_wrapping_store_in_cls_if_not_type.func = (
func # TODO: look for usages, and if not, use __wrapped__
)
# @wraps(func)
wrapper_sig = Sig(func).merge_with_sig(
[dict(name=a, default=None, kind=KO) for a in wrapper_assignments],
ch_to_all_pk=False,
)
# TODO: Re-use double_up_as_factory here
@wrapper_sig
def wrapper(store=None, **kwargs):
if store is None: # then we want a factory
return partial(_func_wrapping_store_in_cls_if_not_type, **kwargs)
else:
wrapped_store_cls = _func_wrapping_store_in_cls_if_not_type(store, **kwargs)
return wrapped_store_cls
# Make sure the wrapper (yes, also the wrapper) has the same key dunders as the func
for a in wrapper_assignments:
v = getattr(func, a, None)
if v is not None:
setattr(wrapper, a, v)
return wrapper
def ensure_set(x):
if isinstance(x, str):
x = [x]
return set(x)
def get_class_name(cls, dflt_name=None):
name = getattr(cls, '__qualname__', None)
if name is None:
name = getattr(getattr(cls, '__class__', object), '__qualname__', None)
if name is None:
if dflt_name is not None:
return dflt_name
else:
raise ValueError(f'{cls} has no name I could extract')
return name
def store_wrap(obj):
if isinstance(obj, type):
@wraps(type(obj), updated=()) # added this: test
class StoreWrap(Store):
@wraps(obj.__init__)
def __init__(self, *args, **kwargs):
persister = obj(*args, **kwargs)
super().__init__(persister)
return StoreWrap
else:
return Store(obj)
def _is_bound(method):
return hasattr(method, '__self__')
def _first_param_is_an_instance_param(params):
return len(params) > 0 and list(params)[0] in self_names
# TODO: Add validation of func: That all but perhaps 1 argument (not counting self) has a default
def _has_unbound_self(func):
"""
Args:
func:
Returns:
>>> def f1(x): ...
>>> assert _has_unbound_self(f1) == 0
>>>
>>> def f2(self, x): ...
>>> assert _has_unbound_self(f2) == 1
>>>
>>> f3 = lambda self, x: True
>>> assert _has_unbound_self(f3) == 1
>>>
>>> class A:
... def bar(self, x): ...
... def foo(dacc, x): ...
>>> a = A()
>>>
>>> _has_unbound_self(a.bar)
0
>>> _has_unbound_self(a.foo)
0
>>> _has_unbound_self(A.bar)
1
>>> _has_unbound_self(A.foo)
0
>>>
"""
try:
params = signature(func).parameters
except ValueError:
# If there was a problem getting the signature, assume it's a signature-less builtin (so not a bound method)
return False
if len(params) == 0:
# no argument, so we can't be wrapping anything!!!
raise ValueError(
"The function has no parameters, so I can't guess which one you want to wrap"
)
elif (
not isinstance(func, type)
and not _is_bound(func)
and _first_param_is_an_instance_param(params)
):
return True
else:
return False
def transparent_key_method(self, k):
return k
def mk_kv_reader_from_kv_collection(
kv_collection, name=None, getitem=transparent_key_method
):
"""Make a KvReader class from a Collection class.
Args:
kv_collection: The Collection class
name: The name to give the KvReader class (by default, it will be kv_collection.__qualname__ + 'Reader')
getitem: The method that will be assigned to __getitem__. Should have the (self, k) signature.
By default, getitem will be transparent_key_method, returning the key as is.
This default is useful when you want to delegate the actual getting to a _obj_of_data wrapper.
Returns: A KvReader class that subclasses the input kv_collection
"""
name = name or kv_collection.__qualname__ + 'Reader'
reader_cls = type(name, (kv_collection, KvReader), {'__getitem__': getitem})
return reader_cls
def raise_disabled_error(functionality):
def disabled_function(*args, **kwargs):
raise ValueError(f'{functionality} is disabled')
return disabled_function
def disable_delitem(o):
if hasattr(o, '__delitem__'):
o.__delitem__ = raise_disabled_error('deletion')
return o
def disable_setitem(o):
if hasattr(o, '__setitem__'):
o.__setitem__ = raise_disabled_error('writing')
return o
def mk_read_only(o):
return disable_delitem(disable_setitem(o))
def is_iterable(x):
return isinstance(x, Iterable)
def add_ipython_key_completions(store):
"""Add tab completion that shows you the keys of the store.
Note: ipython already adds local path listing automatically,
so you'll still get those along with your valid store keys.
"""
def _ipython_key_completions_(self):
return self.keys()
if isinstance(store, type):
store._ipython_key_completions_ = _ipython_key_completions_
else:
setattr(
store,
'_ipython_key_completions_',
types.MethodType(_ipython_key_completions_, store),
)
return store
from dol.util import copy_attrs
from dol.errors import OverWritesNotAllowedError
def disallow_overwrites(store, *, error_msg=None, disable_deletes=True):
assert isinstance(store, type), 'store needs to be a type'
if hasattr(store, '__setitem__'):
def __setitem__(self, k, v):
if k in self:
raise OverWritesNotAllowedError(
'key {} already exists and cannot be overwritten. '
'If you really want to write to that key, delete it before writing'.format(
k
)
)
return super().__setitem__(k, v)
class OverWritesNotAllowedMixin:
"""Mixin for only allowing a write to a key if they key doesn't already exist.
Note: Should be before the persister in the MRO.
>>> class TestPersister(OverWritesNotAllowedMixin, dict):
... pass
>>> p = TestPersister()
>>> p['foo'] = 'bar'
>>> #p['foo'] = 'bar2' # will raise error
>>> p['foo'] = 'this value should not be stored' # doctest: +NORMALIZE_WHITESPACE
Traceback (most recent call last):
...
dol.errors.OverWritesNotAllowedError: key foo already exists and cannot be overwritten.
If you really want to write to that key, delete it before writing
>>> p['foo'] # foo is still bar
'bar'
>>> del p['foo']
>>> p['foo'] = 'this value WILL be stored'
>>> p['foo']
'this value WILL be stored'
"""
@staticmethod
def wrap(cls):
# TODO: Consider moving to trans and making instances wrappable too
class NoOverWritesClass(OverWritesNotAllowedMixin, cls):
...
copy_attrs(NoOverWritesClass, cls, ('__name__', '__qualname__', '__module__'))
return NoOverWritesClass
def __setitem__(self, k, v):
if self.__contains__(k):
raise OverWritesNotAllowedError(
'key {} already exists and cannot be overwritten. '
'If you really want to write to that key, delete it before writing'.format(
k
)
)
return super().__setitem__(k, v)
########################################################################################################################
# Caching keys
# TODO: If a read-one-by-one (vs the current read all implementation) is necessary one day,
# see https://github.com/zahlman/indexify/blob/master/src/indexify.py for ideas
# but probably buffered (read by chunks) version of the later is better.
@store_decorator
def cached_keys(
store=None,
*,
keys_cache: Union[callable, Collection] = list,
iter_to_container=None, # deprecated: use keys_cache instead
cache_update_method='update',
name: str = None, # TODO: might be able to be deprecated since included in store_decorator
__module__=None, # TODO: might be able to be deprecated since included in store_decorator
) -> Union[callable, KvReader]:
"""Make a class that wraps input class's __iter__ becomes cached.
Quite often we have a lot of keys, that we get from a remote data source, and don't want to have to ask for
them again and again, having them be fetched, sent over the network, etc.
So we need caching.
But this caching is not the typical read caching, since it's __iter__ we want to cache, and that's a generator.
So we'll implement a store class decorator specialized for this.
The following decorator, when applied to a class (that has an __iter__), will perform the __iter__ code, consuming
all items of the generator and storing them in _keys_cache, and then will yield from there every subsequent call.
It is assumed, if you're using the cached_keys transformation, that you're dealing with static data
(or data that can be considered static for the life of the store -- for example, when conducting analytics).
If you ever need to refresh the cache during the life of the store, you can to delete _keys_cache like this:
```
del your_store._keys_cache
```
Once you do that, the next time you try to ask something about the contents of the store, it will actually do
a live query again, as for the first time.
Note: The default keys_cache is list though in many cases, you'd probably should use set, or an explicitly
computer set instead. The reason list is used as the default is because (1) we didn't want to assume that
order did not matter (maybe it does to you) and (2) we didn't want to assume that your keys were hashable.
That said, if you're keys are hashable, and order does not matter, use set. That'll give you two things:
(a) your `key in store` checks will be faster (O(1) instead of O(n)) and (b) you'll enforce unicity of keys.
Know also that if you precompute the keys you want to cache with a container that has an update
method (by default `update`) your cache updates will be faster and if the container you use has
a `remove` method, you'll be able to delete as well.
Args:
store: The store instance or class to wrap (must have an __iter__), or None if you want a decorator.
keys_cache: An explicit collection of keys
iter_to_container: The function that will be applied to existing __iter__() and assigned to cache.
The default is list. Another useful one is the sorted function.
cache_update_method: Name of the keys_cache update method to use, if it is an attribute of keys_cache.
Note that this cache_update_method will be used only
if keys_cache is an explicit iterable and has that attribute
if keys_cache is a callable and has that attribute.
The default None
name: The name of the new class
Returns:
If store is:
None: Will return a decorator that can be applied to a store
a store class: Will return a wrapped class that caches it's keys
a store instance: Will return a wrapped instance that caches it's keys
The instances of such key-cached classes have some extra attributes:
_explicit_keys: The actual cache. An iterable container
update_keys_cache: Is called if a user uses the instance to mutate the store (i.e. write or delete).
You have two ways of caching keys:
- By providing the explicit list of keys you want cache (and use)
- By providing a callable that will iterate through your store and collect an explicit list of keys
Let's take a simple dict as our original store.
>>> source = dict(c=3, b=2, a=1)
Specify an iterable, and it will be used as the cached keys
>>> cached = cached_keys(source, keys_cache='bc')
>>> list(cached.items()) # notice that the order you get things is also ruled by the cache
[('b', 2), ('c', 3)]
Specify a callable, and it will apply it to the existing keys to make your cache
>>> list(cached_keys(source, keys_cache=sorted))
['a', 'b', 'c']
You can use the callable keys_cache specification to filter as well!
Oh, and let's demo the fact that if you don't specify the store, it will make a store decorator for you:
>>> cache_my_keys = cached_keys(keys_cache=lambda keys: list(filter(lambda k: k >= 'b', keys)))
>>> d = cache_my_keys(source) # used as to transform an instance
>>> list(d)
['c', 'b']
Let's use that same `cache_my_keys` to decorate a class instead:
>>> cached_dict = cache_my_keys(dict)
>>> d = cached_dict(c=3, b=2, a=1)
>>> list(d)
['c', 'b']
Note that there's still an underlying store (dict) that has the data:
>>> repr(d) # repr isn't wrapped, so you can still see your underlying dict
"{'c': 3, 'b': 2, 'a': 1}"
And yes, you can still add elements,
>>> d['z'] = 26
>>> list(d.items())
[('c', 3), ('b', 2), ('z', 26)]
do bulk updates,
>>> d.update({'more': 'of this'}, more_of='that')
>>> list(d.items())
[('c', 3), ('b', 2), ('z', 26), ('more', 'of this'), ('more_of', 'that')]
and delete...
>>> del d['more']
>>> list(d.items())
[('c', 3), ('b', 2), ('z', 26), ('more_of', 'that')]
But careful! Know what you're doing if you try to get creative. Have a look at this:
>>> d['a'] = 100 # add an 'a' item
>>> d.update(and_more='of that') # update to add yet another item
>>> list(d.items())
[('c', 3), ('b', 2), ('z', 26), ('more_of', 'that')]
Indeed: No 'a' or 'and_more'.
Now... they were indeed added. Or to be more precise, the value of the already existing a was changed,
and a new ('and_more', 'of that') item was indeed added in the underlying store:
>>> repr(d)
"{'c': 3, 'b': 2, 'a': 100, 'z': 26, 'more_of': 'that', 'and_more': 'of that'}"
But you're not seeing it.
Why?
Because you chose to use a callable keys_cache that doesn't have an 'update' method.
When your _keys_cache attribute (the iterable cache) is not updatable itself, the
way updates work is that we iterate through the underlying store (where the updates actually took place),
and apply the keys_cache (callable) to that iterable.
So what happened here was that you have your new 'a' and 'and_more' items, but your cached version of the
store doesn't see it because it's filtered out. On the other hand, check out what happens if you have
an updateable cache.
Using `set` instead of `list`, after the `filter`.
>>> cache_my_keys = cached_keys(keys_cache=set)
>>> d = cache_my_keys(source) # used as to transform an instance
>>> sorted(d) # using sorted because a set's order is not always the same
['a', 'b', 'c']
>>> d['a'] = 100
>>> d.update(and_more='of that') # update to add yet another item
>>> sorted(d.items())
[('a', 100), ('and_more', 'of that'), ('b', 2), ('c', 3)]
This example was to illustrate a more subtle aspect of cached_keys. You would probably deal with
the filter concern in a different way in this case. But the rope is there -- it's your choice on how
to use it.
And here's some more examples if that wasn't enough!
>>> # Lets cache the keys of a dict.
>>> cached_dict = cached_keys(dict)
>>> d = cached_dict(a=1, b=2, c=3)
>>> # And you get a store that behaves as expected (but more speed and RAM)
>>> list(d)
['a', 'b', 'c']
>>> list(d.items()) # whether you iterate with .keys(), .values(), or .items()
[('a', 1), ('b', 2), ('c', 3)]
This is where the keys are stored:
>>> d._keys_cache
['a', 'b', 'c']
>>> # Let's demo the iter_to_container argument. The default is "list", which will just consume the iter in order
>>> sorted_dict = cached_keys(dict, keys_cache=list)
>>> s = sorted_dict({'b': 3, 'a': 2, 'c': 1})
>>> list(s) # keys will be in the order they were defined
['b', 'a', 'c']
>>> sorted_dict = cached_keys(dict, keys_cache=sorted)
>>> s = sorted_dict({'b': 3, 'a': 2, 'c': 1})
>>> list(s) # keys will be sorted
['a', 'b', 'c']
>>> sorted_dict = cached_keys(dict, keys_cache=lambda x: sorted(x, key=len))
>>> s = sorted_dict({'bbb': 3, 'aa': 2, 'c': 1})
>>> list(s) # keys will be sorted according to their length
['c', 'aa', 'bbb']
If you change the keys (adding new ones with __setitem__ or update, or removing with pop or popitem)
then the cache is recomputed (the first time you use an operation that iterates over keys)
>>> d.update(d=4) # let's add an element (try d['d'] = 4 as well)
>>> list(d)
['a', 'b', 'c', 'd']
>>> d['e'] = 5
>>> list(d.items()) # whether you iterate with .keys(), .values(), or .items()
[('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e', 5)]
>>> @cached_keys
... class A:
... def __iter__(self):
... yield from [1, 2, 3]
>>> # Note, could have also used this form: AA = cached_keys(A)
>>> a = A()
>>> list(a)
[1, 2, 3]
>>> a._keys_cache = ['a', 'b', 'c'] # changing the cache, to prove that subsequent listing will read from there
>>> list(a) # proof:
['a', 'b', 'c']
>>>
>>> # Let's demo the iter_to_container argument. The default is "list", which will just consume the iter in order
>>> sorted_dict = cached_keys(dict, keys_cache=list)
>>> s = sorted_dict({'b': 3, 'a': 2, 'c': 1})
>>> list(s) # keys will be in the order they were defined
['b', 'a', 'c']
>>> sorted_dict = cached_keys(dict, keys_cache=sorted)
>>> s = sorted_dict({'b': 3, 'a': 2, 'c': 1})
>>> list(s) # keys will be sorted
['a', 'b', 'c']
>>> sorted_dict = cached_keys(dict, keys_cache=lambda x: sorted(x, key=len))
>>> s = sorted_dict({'bbb': 3, 'aa': 2, 'c': 1})
>>> list(s) # keys will be sorted according to their length
['c', 'aa', 'bbb']
"""
arguments = {k: v for k, v in locals().items() if k != 'arguments'}
store = arguments.pop('store')
class_trans = partial(_cached_keys, **arguments)
arguments['name'] = arguments['name'] or store.__qualname__ + 'Wrapped'
return Store.wrap(store, class_trans=class_trans)
def _cached_keys(
store,
keys_cache: Union[callable, Collection] = list,
iter_to_container=None, # deprecated: use keys_cache instead
cache_update_method='update',
name: str = None, # TODO: might be able to be deprecated since included in store_decorator
__module__=None, # TODO: might be able to be deprecated since included in store_decorator
):
if iter_to_container is not None:
assert callable(iter_to_container)
warn(
"The argument name 'iter_to_container' is being deprecated in favor "
"of the more general 'keys_cache'"
)
# assert keys_cache == iter_to_container
assert isinstance(
store, type
), f'store_cls must be a type, was a {type(store)}: {store}'
# name = name or 'IterCached' + get_class_name(store_cls)
name = name or get_class_name(store)
__module__ = __module__ or getattr(store, '__module__', None)
class cached_cls(store):
_keys_cache = None
cached_cls.__name__ = name
# cached_cls = type(name, (store_cls,), {"_keys_cache": None})
# The following class is not the class that will be returned, but the class from which we'll take the methods
# that will be copied in the class that will be returned.
# @_define_keys_values_and_items_according_to_iter
class CachedIterMethods:
_explicit_keys = False
_updatable_cache = False
_iter_to_container = None
if hasattr(keys_cache, cache_update_method):
_updatable_cache = True
if is_iterable(
keys_cache
): # if keys_cache is iterable, it is the cache instance itself.
_keys_cache = keys_cache
_explicit_keys = True
elif callable(keys_cache):
# if keys_cache is not iterable, but callable, we'll use it to make the keys_cache from __iter__
_iter_to_container = keys_cache
@lazyprop
def _keys_cache(self):
# print(iter_to_container)
return keys_cache(
super(cached_cls, self).__iter__()
) # TODO: Should it be iter(super(...)?
@property
def _iter_cache(self): # for back-compatibility
warn(
'The new name for `_iter_cache` is `_keys_cache`. Start using that!',
DeprecationWarning,
)
return self._keys_cache
def __iter__(self):
# if getattr(self, '_keys_cache', None) is None:
# self._keys_cache = iter_to_container(super(cached_cls, self).__iter__())
yield from self._keys_cache
def __len__(self):
return len(self._keys_cache)
def __contains__(self, k):
return k in self._keys_cache
# The write and update stuff ###################################################################
if _updatable_cache:
def update_keys_cache(self, keys):
"""updates the keys by calling the"""
update_func = getattr(self._keys_cache, cache_update_method)
update_func(self._keys_cache, keys)
update_keys_cache.__doc__ = (
'Updates the _keys_cache by calling its {} method'
)
else:
def update_keys_cache(self, keys):
"""Updates the _keys_cache by deleting the attribute"""
try:
del self._keys_cache
# print('deleted _keys_cache')
except AttributeError:
pass
def __setitem__(self, k, v):
super(cached_cls, self).__setitem__(k, v)
# self.store[k] = v
if (
k not in self
): # just to avoid deleting the cache if we already had the key
self.update_keys_cache((k,))
# Note: different construction performances: (k,)->10ns, [k]->38ns, {k}->50ns
def update(self, other=(), **kwds):
# print(other, kwds)
# super(cached_cls, self).update(other, **kwds)
super_setitem = super(cached_cls, self).__setitem__
for k in other:
# print(k, other[k])
super_setitem(k, other[k])
# self.store[k] = other[k]
self.update_keys_cache(other)
for k, v in kwds.items():
# print(k, v)
super_setitem(k, v)
# self.store[k] = v
self.update_keys_cache(kwds)
def __delitem__(self, k):
self._keys_cache.remove(k)
super(cached_cls, self).__delitem__(k)
# And this is where we add all the needed methods (for example, no __setitem__ won't be added if the original
# class didn't have one in the first place.
special_attrs = {
'update_keys_cache',
'_keys_cache',
'_explicit_keys',
'_updatable_cache',
}
for attr in special_attrs | (
AttrNames.KvPersister & attrs_of(cached_cls) & attrs_of(CachedIterMethods)
):
setattr(cached_cls, attr, getattr(CachedIterMethods, attr))
if __module__ is not None:
cached_cls.__module__ = __module__
if hasattr(store, '__doc__'):
cached_cls.__doc__ = store.__doc__
return cached_cls
cache_iter = cached_keys # TODO: Alias, partial it and make it more like the original, for back compatibility.
@store_decorator
def catch_and_cache_error_keys(
store=None,
*,
errors_caught=Exception,
error_callback=None,
use_cached_keys_after_completed_iter=True,
):
"""Store that will cache keys as they're accessed, separating those that raised errors and those that didn't.
Getting a key will still through an error, but the access attempts will be collected in an ._error_keys attribute.