-
Notifications
You must be signed in to change notification settings - Fork 3
/
pycond.py
1371 lines (1094 loc) · 39.6 KB
/
pycond.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
"""
Condition parser
See README.
See Tests.
DEV Notes:
f_xyz denotes a function (we work a lot with lambdas and partials)
Q: Why not pass state inst
A: The **kw for all functions at run time are for the custom lookup feature:
model = {'eve': {'last_host': 'somehost'}}
def my_lu(k, v, req, user, model=model):
return (model.get(user) or {}).get(k), req[v]
f = pc.pycond('last_host eq host', lookup=my_lu)
req = {'host': 'somehost'}
assert f(req=req, user='joe') == False
assert f(req=req, user='eve') == True
"""
from __future__ import print_function
import os
from datetime import datetime
import operator
import sys
import inspect
import json
from functools import partial
from ast import literal_eval
_is = isinstance
nil = '\x01'
PY2 = sys.version_info[0] == 2
# is_str = lambda s: _is(s, basestring if PY2 else (bytes, str))
if PY2:
def is_str(s):
return _is(s, basestring)
def sig_args(f):
return inspect.getargspec(getattr(f, 'func', f)).args
else:
def is_str(s):
return _is(s, (bytes, str))
def sig_args(f):
return list(inspect.signature(f).parameters.keys())
bbb = bool
def xbool(o):
print(o)
return bbb(o)
# fmt:off
# from dir(operator):
_ops = {
'nr': [
['add' , '+' ] ,
['and_' , '&' ] ,
['eq' , '==' ] ,
['floordiv' , '//' ] ,
['ge' , '>=' ] ,
['gt' , '>' ] ,
['iadd' , '+=' ] ,
['iand' , '&=' ] ,
['ifloordiv' , '//=' ] ,
['ilshift' , '<<=' ] ,
['imod' , '%=' ] ,
['imul' , '*=' ] ,
['ior' , '|=' ] ,
['ipow' , '**=' ] ,
['irshift' , '>>=' ] ,
['is_' , 'is' ] ,
['is_not' , 'is' ] ,
['isub' , '-=' ] ,
['itruediv' , '/=' ] ,
['ixor' , '^=' ] ,
['le' , '<=' ] ,
['lshift' , '<<' ] ,
['lt' , '<' ] ,
['mod' , '%' ] ,
['mul' , '*' ] ,
['ne' , '!=' ] ,
['or_' , '|' ] ,
['pow' , '**' ] ,
['rshift' , '>>' ] ,
['sub' , '-' ] ,
['truediv' , '/' ] ,
['xor' , '^' ] ,
['itemgetter' , '' ] , # 'itemgetter(item, ...) --> itemgetter object\n\nReturn a callable object that fetches the given item(s) from its operand.\nAfter f = itemgetter(2), the call f(r) returns r[2].\nAfter g = itemgetter(2, 5, 3), the call g(r) returns (r[2], r[5], r[3])',
['length_hint', '' ] , #'Return an estimate of the number of items in obj.\n\nThis is useful for presizing containers when building from an iterable.\n\nIf the object supports len(), the result will be exact.\nOtherwise, it may over- or under-estimate by an arbitrary amount.\nThe result will be an integer >= 0.',
],
'str': [
['attrgetter' , '' ] , # "attrgetter(attr, ...) --> attrgetter object\n\nReturn a callable object that fetches the given attribute(s) from its operand.\nAfter f = attrgetter('name') , the call f(r) returns r.name.\nAfter g = attrgetter('name' , 'date') , the call g(r) returns (r.name , r.date).\nAfter h = attrgetter('name.first' , 'name.last') , the call h(r) returns\n(r.name.first , r.name.last)." ,
['concat' , '+' ] ,
['contains' , '' ] , # 'Same as b in a (note reversed operands).'] ,
['countOf' , '' ] , #'Return the number of times b occurs in a.'] ,
['iconcat' , '+=' ] ,
['indexOf' , '' ] , #'Return the first index of b in a.'] ,
['methodcaller', '' ] , # "methodcaller(name, ...) --> methodcaller object\n\nReturn a callable object that calls the given method on its operand.\nAfter f = methodcaller('name'), the call f(r) returns r.name().\nAfter g = methodcaller('name', 'date', foo=1), the call g(r) returns\nr.name('date', foo=1).",
],
}
# fmt:on
OPS = {}
OPS_SYMBOLIC = {}
# extending operators with those:
def truthy(k, v=None):
return operator.truth(k)
def falsy(k, v=None):
return not truthy(k, v)
def _in(a, b):
return a in b
def get_ops():
return _ops
def add_built_in_ops():
OPS['truthy'] = truthy
OPS['falsy'] = falsy
OPS['in'] = _in
def clear_ops():
OPS.clear()
OPS_SYMBOLIC.clear()
def parse_ops():
"""Sets up OPs from scratch, using txt opts only"""
clear_ops()
for t in 'str', 'nr':
for k, alias in _ops[t]:
f = getattr(operator, k, None)
# the list is python3.7 - not all have all:
if f:
OPS[k] = f
if alias:
OPS_SYMBOLIC[alias] = f
add_built_in_ops()
def ops_use_symbolic(allow_single_eq=False):
OPS.clear()
OPS.update(OPS_SYMBOLIC)
add_built_in_ops()
if allow_single_eq:
OPS['='] = OPS['==']
def ops_use_symbolic_and_txt(allow_single_eq=False):
parse_ops()
OPS.update(OPS_SYMBOLIC)
if allow_single_eq:
OPS['='] = OPS['==']
def ops_reset():
parse_ops()
ops_use_txt = ops_reset
ops_use_txt()
# see api below for these:
OPS_HK_APPLIED = False
# default lookup of keys here - no, module does NOT need to have state.
# its a convenience thing, see tests:
# Discurraged to be used in non-cooperative async situations, since clearly not thread safe - just pass the state into pycond:
State = {}
class Getters:
def state_get_deep(key, val, cfg, state=State, deep='.', **kw):
"""
Hotspot!
"""
# FIXME: why split at runtime?
# key maybe already path tuple - or string with deep as seperator:
# Also the try to get list items when part is int can be checked at build time!
# parts = key.split(deep) if _is(key, str) else list(key)
parts = key.split(deep) if _is(key, str) else key
for part in parts:
try:
state = state.get(part)
except AttributeError as ex:
try:
i = int(part)
state = state[i]
except ValueError as ex: # i no list index, we try attrs:
state = getattr(state, part, None)
except IndexError as ex:
state = None
if not state:
break
return state, val
def state_get(key, val, cfg, state=State, **kw):
# a lookup function can modify key AND value, i.e. returns both:
if _is(key, tuple):
return state_get_deep(key, val, cfg, state, **kw)
else:
return state.get(key), val # default k, v access function
def dbg_get(key, val, cfg, state=State, *a, **kw):
res = Getters.state_get(key, val, cfg, state, *a, **kw)
val = 'FALSES' if val == FALSES else val
out('Lookup:', key, val, '->', res[0])
return res
def _diginto(state, key, sep):
"""Helper which is, on the first matching state structure,
delivering the keys we needed"""
g = ()
parts = key.split(sep) if _is(key, str) else key
for part in parts:
try:
state = state.get(part)
g += (part,)
except AttributeError as ex:
try:
i = int(part)
state = state[i]
g += (i,)
except ValueError as ex: # i no list index, we try attrs:
state = getattr(state, part, None)
g += ((part, 0),) # attrgetter below
except IndexError as ex:
state = None
if not state:
return None, None
return state, g
_get_deep2_cache = {}
def get_deep2(key, val, cfg, state, deep='.', _c=_get_deep2_cache, **kw):
"""
Here we cache the split result
"""
funcs = _c.get(key)
if funcs:
try:
if funcs[0] == True:
for f in funcs[1:]:
state = state[f]
else:
for f in funcs:
state = f(state) # we have itemgetters and attrsgettr
return state, val
except Exception:
return None, val
state, g = Getters._diginto(state, key, sep=deep)
if state is None:
return state, val
# we have matching structure => invest in assembling the getter functions
# If there are no getattr (=>no tuple), then just []-ing the values is even faster then using itemgetter:
# so we mark those with a True in the beginning and just remember the values:
if len(_c) > 1000000:
_c.clear() # safety belt
if not any([i for i in g if _is(i, tuple)]):
_c[key] = g = list(g)
g.insert(0, True)
else:
a, i = operator.attrgetter, operator.itemgetter
_c[key] = [a(f[0]) if isinstance(f, tuple) else i(f) for f in g]
return state, val
_get_deep3_cache = {}
def get_deep_evl(key, val, cfg, state, deep='.', _c=_get_deep3_cache, **kw):
"""
Fastest, but we must disallow ( )
"""
funcs = _c.get(key)
if funcs:
try:
return funcs(state), val
except Exception:
return None, val
state, g = Getters._diginto(state, key, sep=deep)
if state is None:
return state, val
g = [
f'["{p}"]' if _is(p, str) else f'.{p[0]}' if _is(p, tuple) else f'[{p}]'
for p in g
]
g = ''.join(g)
g = f'lambda s: s{g}'
if '(' in g and ')' in g:
g = 'lambda s: None'
if len(_c) > 1000000:
_c.clear() # safety belt
_c[key] = eval(g)
return state, val
def clear_caches():
Getters._get_deep2_cache.clear()
Getters._get_deep3_cache.clear()
state_get_deep = Getters.state_get_deep
dbg_get = Getters.dbg_get
state_get = Getters.state_get
# if val in these we deliver False:
# FIXME: wtf? was this intended a feature, to allow modifications of python's default?
# but y then immutable?
FALSES = (None, False, '', 0, {}, [], ())
def out(*m):
return print(' '.join([str(s) for s in m]))
OR, AND, OR_NOT, AND_NOT, XOR = 0, 1, 2, 3, 4
def comb(op, lazy_on, negate=None):
"""Absolut Hotspot. Fastest way to do it."""
def _comb(
f,
g,
op=op,
lazy_on=lazy_on,
negate=negate,
ands={AND, AND_NOT},
ors={OR, OR_NOT},
fr=nil,
**kw,
):
# try:
if 1:
fr = f(**kw)
if fr:
if lazy_on:
return True
elif lazy_on is False:
return False
if op == AND:
return fr and g(**kw)
elif op == OR:
return fr or g(**kw)
elif op == AND_NOT:
return fr and not g(**kw)
elif op == OR_NOT:
return fr or not g(**kw)
else:
return fr is not g(**kw)
# except Async as ex:
# h = ex.args[0][0]
# if fr == nil:
# fgr = [op, h, g]
# else:
# fgr = [op, bool(fr), h]
# ex.args[0][0] = fgr
# raise ex
return _comb
# fmt: off
COMB_OPS = {
'or': comb(OR, True),
'and': comb(AND, False),
'or_not': comb(OR_NOT, True, True),
'and_not': comb(AND_NOT, False, True),
'xor': comb(XOR, None),
}
# fmt: on
# those from user space are also replaced at tokenizing time:
NEG_REV = {'not rev': 'not_rev', 'rev not': 'rev_not'}
def is_deep_list_path(key):
"""
Identify the first list is a key, i.e. should actually be a tuple:
[[['a', 'b', 0, 'c'], 'eq', 1], 'and', 'a'] -> should be:
[[('a', 'b', 0, 'c'), 'eq', 1], 'and', 'a']
When transferred over json we can't do paths as tuples
We find if have a deep path by excluding every other option:
"""
if not _is(key, list):
return
if any([k for k in key if not _is(k, (str, int))]):
return
if not (len(key)) > 1:
return
if key[1] in COMB_OPS:
return
if key[1] in OPS:
return
if len(key) == 4 and key[1] in OP_PREFIXES:
return
return True
def prepare(cond, cfg, nfo):
# resolve any conditions builds using the same subcond refs many times -
# i.e. remove those refs can create unique items we can modify during parsing:
# NOTE: This is build time, not eval time, i.e. does not hurt much:
cond = literal_eval(str(cond))
res = parse_struct_cond(cond, cfg, nfo)
p = cfg.get('prefix', None)
if not p:
return res
def get_prefix(prefix, res):
def p(prefix, res, *a, state=State, **kw):
if 'state_root' not in kw:
kw['state_root'] = state
state = state.get(prefix)
return res(*a, state=state, **kw)
return partial(p, prefix=prefix, res=res)
return get_prefix(p, res)
KEY_STR_TYP, KEY_TPL_TYP, KEY_LST_TYP, KEY_BOOL_TYP = 1, 2, 3, 4
def key_type(key):
if _is(key, str):
return KEY_STR_TYP
elif _is(key, bool):
return KEY_BOOL_TYP
elif _is(key, tuple):
return KEY_TPL_TYP
elif _is(key, list) and is_deep_list_path(key):
return KEY_LST_TYP
return None
def parse_struct_cond(cond, cfg, nfo):
"""this expects json style conditions
Examples:
a and b or c - then we map those to the truthy op
a eq foo and b eq bar
[a eq foo] and b
[a eq foo] and [b is baz]
"""
f1 = None
while cond:
key = cond.pop(0)
kt = key_type(key)
if kt:
if kt == KEY_STR_TYP:
if f1 and key in COMB_OPS:
# cond: b eq bar
return partial(
COMB_OPS[key],
f1,
parse_struct_cond(cond, cfg, nfo),
)
elif kt == KEY_BOOL_TYP:
def f1(*a, _=key, **kw):
return bool(_)
continue
elif kt == KEY_LST_TYP:
key = tuple(key)
# atomic condition:
ac = [key]
while cond:
if _is(cond[0], str) and cond[0] in COMB_OPS:
break
ac.append(cond.pop(0))
f1 = atomic_cond(ac, cfg, nfo)
# now a combinator MUST come:
else:
# key is not a key but the first cond:
f1 = parse_struct_cond(key, cfg, nfo)
return f1
# _parse_cond = x_parse_cond
OP_PREFIXES = {'not', 'not_rev', 'rev_not', 'rev'}
def atomic_cond(cond, cfg, nfo):
# ------------------------------------------------ Handle atomic conditions
# cond like ['foo', 'not', 'le', '10']
key = cond.pop(0)
# autocondition for key only: not rev contains (None, 0, ...):
if len(cond) == 0:
comp = 'truthy'
cond.insert(0, 0)
cond.insert(0, comp)
elif len(cond) == 1 and key == 'not':
key = cond.pop(0)
comp = 'falsy'
cond.insert(0, 0)
cond.insert(0, comp)
nfo['keys'].add(key)
# prefixes infront of the operator: not and rev - in any combi:
# if sep was spc we replaced them at tokenizing with e.g. not_rev
not_, rev_ = False, False
# we accept [not] [rev] and also [rev] [not]
for i in 1, 2:
if cond[0] in OP_PREFIXES:
nr = cond.pop(0)
not_ = True if 'not' in nr else not_
rev_ = True if 'rev' in nr else rev_
op = cond.pop(0)
f_op = OPS.get(op)
if not f_op:
raise Exception('Operator %s not known' % op)
f_ot = cfg.get('ops_thru')
if f_ot:
f_op = partial(f_ot, f_op)
val = cond.pop(0)
# foo eq "42" -> tokenized to 'foo', 'eq', 'str:42' -> should now not
# become number 42:
if str(val).startswith('str:'):
val = str(val[4:])
else:
if cfg.get('autoconv', True): # can do this in the build phase already:
val = py_type(val) # '42' -> 42
fp_lookup = f_from_lookup_provider(key, val, cfg, nfo)
if not fp_lookup:
f_lookup = cfg['lookup']
if 'cfg' in cfg['lookup_args']:
fp_lookup = partial(f_lookup, key, val, cfg=cfg)
else:
fp_lookup = partial(f_lookup, key, val)
# we do what we can in the building not the evaluation phase:
acl = cfg.get('autoconv_lookups', False)
# try save stackframes and evaluations for the eval phase:
if any((acl, rev_, not_)):
f_res = partial(f_atomic_arn, f_op, fp_lookup, key, val, not_, rev_, acl)
else:
# normal case:
f_res = partial(f_atomic, f_op, fp_lookup, key, val)
return f_res
# ------------------------------------------------------------ Evaluation Phase
# we do these two versions for with cfg and w/o to safe a stackframe
# (otherwise a lambda would be required - or checking for cfg at each eval)
# when you change, check this number for effect on perf:
# 2 ~/GitHub/pycond/tests $ python test_pycond.py Perf.test_perf | grep 'fast
# ('With fast lookup function:', 2.1161916086894787)
def f_atomic(f_op, fp_lookup, key, val, **kw):
# normal case - be fast:
try:
return f_op(*fp_lookup(**kw))
except Async:
raise
# except Exception as ex:
# msg = ''
# if fp_lookup != state_get:
# msg = '. Note: A custom lookup function must return two values:'
# msg += ' The cur. value for key from state plus the compare value.'
# raise Exception(
# '%s %s. key: %s, compare val: %s%s'
# % (ex.__class__.__name__, str(ex), key, val, msg)
# )
def f_atomic_arn(f_op, fp_lookup, key, val, not_, rev_, acl, **kw):
# when some switches are set in cfg:
k, v = fp_lookup(**kw)
if acl is True:
k = py_type(k)
if rev_ is True:
k, v = v, k
return not f_op(k, v) if not_ is True else f_op(k, v)
def f_from_lookup_provider(key, val, cfg, nfo):
req_p = prefixed_lookup_funcs and cfg.get('prefixed_lookup_funcs', True)
has_p = ':' in key
if not has_p and req_p:
return
key = key[1:] if key[0] == ':' else key
func = find_func(key, cfg)
if not func:
if req_p or has_p:
raise MissingLookupFunction('Lookup provider function not found:', key)
# prefix was switched off, it has none:
return
# the condition functions may be parametrized:
func_params = cfg.get('params', {}).get(key)
if func_params:
func = partial(func, **func_params)
# Multiple sigs are accepted:
sig = inspect.getfullargspec(func)
req_params = len(sig.args) - (len(sig.defaults) if sig.defaults else 0)
if req_params == 0 and not sig.varargs:
# fixed ones, like dt:minutes
# FIXME: make faster and allow a small sig function for those
def f(k, v, cfg, state=State, func_=func, **kw):
return func_(), v
func = f
elif req_params == 1:
if sig.varkw:
def fkw(k, v, cfg, state=State, func_=func, **kw):
return func_(state, cfg=cfg, **kw), v
func = fkw
else:
def f(k, v, cfg, state=State, func_=func, **kw):
return func_(state), v
func = f
def lp_func(
key_=key,
val_=val,
cfg=cfg,
state=State,
asyn_=key in cfg.get('asyn', []),
func_=func,
**kw,
):
if asyn_ and not cache_get(kw, CACHE_KEY_ASYNC):
cache_set(kw, CACHE_KEY_ASYNC, True)
# will trigger the prefix replacement in the async greenlet again:
kw.pop('state_root', 0)
# Exception bubbling up, triggering a re-run in own greenlet:
raise Async([kw])
kv = cache_get(kw, key_, val_)
if kv:
return kv
res = func_(key_, val_, cfg, state, **kw)
cache_set(kw, key_, res[0])
return res
return lp_func
# ----------------------------------------------- helpers for lookup provider functions
prefixed_lookup_funcs = True
class MissingLookupFunction(Exception):
"""Build time exception"""
def find_func(key, cfg):
"""
Searching all namespaces for a lookup provider function
"""
l, func = ['lookup_provider', 'lookup_provider_dict'], None
providers = [cfg.get(l[0]), cfg.get(l[1]), Extensions]
for p in providers:
g = (lambda m, k, d: m.get(k, d)) if isinstance(p, dict) else getattr
for part in key.split(':'):
if p is None:
break
p = g(p, part, None)
func = p['func'] if isinstance(p, dict) else p
if func:
return func
# -------------------------------------------------------------------------- Public API
# (def qualify has it's own section)
class Extensions:
class env:
def __getattr__(self, k, v=None):
return lambda k=k, v=v: os.environ.get(k, v)
env = env()
class dt:
pass
class utc:
pass
for k in ('second', 'minute', 'hour', 'day', 'month', 'year'):
setattr(dt, k, lambda k=k: getattr(datetime.now(), k))
setattr(utc, k, lambda k=k: getattr(datetime.utcnow(), k))
def sorted_keys(l):
a = [i for i in l if _is(i, tuple)]
b = l - set(a)
return sorted(list(b)) + sorted(a, key=len)
def deserialize_str(cond, check_dict=False, **cfg):
try:
return json.loads(cond), cfg
except:
pass
cfg['brkts'] = brkts = cfg.get('brkts', '[]')
if check_dict:
# in def qualify we accept textual (flat) dicts.
# The cond strings (v) will be sent again into this method.
p = cond.split(':', 1)
if len(p) > 1 and ' ' not in p[0] and brkts[0] not in p[0]:
kvs = [c.strip().split(':', 1) for c in cond.split(',')]
return dict([(k.strip(), v.strip()) for k, v in kvs]), cfg
sep = cfg.pop('sep', KV_DELIM)
if cond.startswith('deep:'):
cond = cond.split('deep:', 1)[1].strip()
cfg['deep'] = '.'
cond = tokenize(cond, sep=sep, brkts=brkts)
return to_struct(cond, cfg['brkts']), cfg
def make_filter(cond, lookup=state_get, **cfg):
"""convenience function for filters"""
return lambda state, f=parse_cond(cond, lookup=lookup, **cfg)[0]: f(state=state)
def parse_cond(cond, lookup=state_get, **cfg):
"""Main function.
see tests
"""
nfo = {'keys': set()}
if is_str(cond):
cond, cfg = deserialize_str(cond, **cfg)
if cfg.get('get_struct'):
return cond, cfg
if cfg.get('deep'):
lookup = partial(state_get_deep, deep=cfg['deep'])
elif cfg.get('deep2'):
lookup = partial(Getters.get_deep2, deep=cfg['deep2'])
elif cfg.get('deep3'):
lookup = partial(Getters.get_deep_evl, deep=cfg['deep3'])
cfg['lookup'] = lookup
cfg['lookup_args'] = sig_args(lookup)
cond = prepare(cond, cfg, nfo)
nfo['keys'] = sorted_keys(nfo['keys'])
provider = cfg.get('ctx_provider')
if provider:
nfo['complete_ctx'] = complete_ctx_data(nfo['keys'], provider=provider)
# if lp:
# cond = partial(post_hook, cond)
return cond, nfo
def complete_ctx_data(keys, provider):
def _getter(ctx, keys, provider):
for k in keys:
v = ctx.get(k, nil)
if v != nil:
continue
ctx[k] = getattr(provider, k)(ctx)
return ctx
return partial(_getter, keys=keys, provider=provider)
# where we store intermediate results, e.g. from lookup providers:
CACHE_KEY = 'pyc_cache'
CACHE_KEY_ASYNC = 'async'
def pop_cache(kw):
"""prefix e.g. "payload" in full messages with headers"""
# if prefix:
# = state.get(prefix)
return kw.pop(CACHE_KEY, 0)
def cache_set(kw, k, v):
kw[CACHE_KEY][k] = v
def cache_get(kw, key, val=None):
try:
cache = kw[CACHE_KEY]
except Exception as ex:
kw[CACHE_KEY] = cache = {}
v = cache.get(key, nil)
if v != nil:
return v, val
def pycond(cond, *a, **cfg):
"""condition function - for those who don't need meta infos"""
return parse_cond(cond, *a, **cfg)[0]
def run_all_ops_thru(f_hook):
"""wraps ALL operator evals within a custom function"""
global OPS_HK_APPLIED
if OPS_HK_APPLIED == f_hook:
return
def ops_wrapper(f_op, f_hook, a, b):
return f_hook(f_op, a, b)
ops = OPS.keys()
for k in ops:
OPS[k] = partial(ops_wrapper, OPS[k], f_hook)
OPS_HK_APPLIED = f_hook
def py_type(v):
if not is_str(v):
return v
def _(v):
# returns a str(v) if float and int do not work:
for t in float, int, str:
try:
# prevent converstion to scientific format:
# key, eq, '100688907740199323' would fail:
if t == float and int(float(v)) == float(v):
return int(v)
return t(v)
except:
pass
return (
True if v == 'true' else False if v == 'false' else None if v == 'None' else _(v)
)
# ---------------------- Following Code Only for Parsing STRING Conditions Into Structs
KV_DELIM = ' ' # default seperator for strings
def tokenize(cond, sep=KV_DELIM, brkts=('[', ']')):
"""walk throug a single string expression"""
# '[[ a' -> '[ [ a', then split
esc, escaped, have_apo_seps = [], [], False
# remove the space from the ops here, comb ops are like 'and_not':
for op in COMB_OPS:
if '_' in op:
cond = cond.replace(op.replace('_', sep), op)
for op, repl in NEG_REV.items():
cond = cond.replace(op, repl)
cond = [c for c in cond]
r = []
while cond:
c = cond.pop(0)
have_apo = False
for apo in '"', "'":
if c != apo:
continue
have_apo = True
r += 'str:'
while cond and cond[0] != apo: # and r[-1] != '\\':
c = cond.pop(0)
if c == sep:
c = '__sep__'
have_apo_seps = True
r += c
if cond:
cond.pop(0)
continue
if have_apo:
continue
# esape:
if c == '\\':
c = cond.pop(0)
if c in escaped:
key = esc[escaped.index(c)]
else:
escaped.append(c)
key = '__esc__%s' % len(escaped)
esc.append(key)
r += key
continue
isbr = False
if c in brkts:
isbr = True
if r and r[-1] != sep:
r += sep
r += c
if isbr and cond and cond[0] != sep:
r += sep
cond = ''.join(r)
# replace back the escaped stuff:
if not esc:
# be fast:
res = cond.split(sep)
else:
# fastets before splitting:
cond = cond.replace(sep, '__ESC__')
for i in range(len(esc)):
cond = cond.replace(esc[i], escaped[i])
res = cond.split('__ESC__')
# replace back the previously excluded stuff in apostrophes:
if have_apo_seps:
res = [part.replace('__sep__', sep) for part in res]
return res
def to_struct(cond, brackets='[]'):
"""Recursively scanning through a tokenized expression and building the
condition function step by step
"""
openbrkt, closebrkt = brackets
expr1 = None
res = []
while cond:
part = cond.pop(0)
if part == openbrkt:
lev = 1
inner = []
while not (lev == 1 and cond[0] == closebrkt):
inner.append(cond.pop(0))
if inner[-1] == openbrkt:
lev += 1
elif inner[-1] == closebrkt:
lev -= 1
cond.pop(0)
res.append(to_struct(inner, brackets))
else:
res.append(part)
return res
# ----------------------------------------------------------------------------- qualify
def add_cache_then_run(f, *a, **kw):
"""
When running an item through we want a cache for
- lookup provider results
- sub cond evaluations
"""
if CACHE_KEY not in kw:
kw[CACHE_KEY] = {}
return f(*a, **kw)
def norm(cond):
"""
Do we have a single condition, which we return double bracketted or a list of conds?
We also return if the cond is_single
"""
# given as ['foo', 'eq', 'bar'] instead [['foo', 'eq', 'bar']]?
kt = key_type(cond[0])
if kt in [True, False]:
return [cond], True
if kt:
cond = [cond]