/
predicates.py
1275 lines (925 loc) · 24.9 KB
/
predicates.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
# -*- coding: utf-8 -*-
"""Predicate functions that return boolean evaluations of objects.
.. versionadded:: 2.0.0
"""
from __future__ import absolute_import
import datetime
from itertools import islice
import json
import operator
import re
from types import BuiltinFunctionType
import pydash as pyd
from .helpers import NoValue, callit, iterator
from ._compat import (
builtins,
integer_types,
izip,
number_types,
string_types
)
__all__ = (
'eq',
'gt',
'gte',
'lt',
'lte',
'in_range',
'is_associative',
'is_blank',
'is_boolean',
'is_builtin',
'is_date',
'is_decreasing',
'is_dict',
'is_empty',
'is_equal',
'is_equal_with',
'is_error',
'is_even',
'is_float',
'is_function',
'is_increasing',
'is_indexed',
'is_instance_of',
'is_integer',
'is_iterable',
'is_json',
'is_list',
'is_match',
'is_match_with',
'is_monotone',
'is_nan',
'is_negative',
'is_none',
'is_number',
'is_object',
'is_odd',
'is_positive',
'is_reg_exp',
'is_set',
'is_strictly_decreasing',
'is_strictly_increasing',
'is_string',
'is_tuple',
'is_zero',
)
RegExp = type(re.compile(''))
def eq(value, other):
"""Checks if :attr:`value` is equal to :attr:`other`.
Args:
value (mixed): Value to compare.
other (mixed): Other value to compare.
Returns:
bool: Whether :attr:`value` is equal to :attr:`other`.
Example:
>>> eq(None, None)
True
>>> eq(None, '')
False
>>> eq('a', 'a')
True
>>> eq(1, str(1))
False
.. versionadded:: 4.0.0
"""
return value is other
def gt(value, other):
"""Checks if `value` is greater than `other`.
Args:
value (number): Value to compare.
other (number): Other value to compare.
Returns:
bool: Whether `value` is greater than `other`.
Example:
>>> gt(5, 3)
True
>>> gt(3, 5)
False
>>> gt(5, 5)
False
.. versionadded:: 3.3.0
"""
return value > other
def gte(value, other):
"""Checks if `value` is greater than or equal to `other`.
Args:
value (number): Value to compare.
other (number): Other value to compare.
Returns:
bool: Whether `value` is greater than or equal to `other`.
Example:
>>> gte(5, 3)
True
>>> gte(3, 5)
False
>>> gte(5, 5)
True
.. versionadded:: 3.3.0
"""
return value >= other
def lt(value, other):
"""Checks if `value` is less than `other`.
Args:
value (number): Value to compare.
other (number): Other value to compare.
Returns:
bool: Whether `value` is less than `other`.
Example:
>>> lt(5, 3)
False
>>> lt(3, 5)
True
>>> lt(5, 5)
False
.. versionadded:: 3.3.0
"""
return value < other
def lte(value, other):
"""Checks if `value` is less than or equal to `other`.
Args:
value (number): Value to compare.
other (number): Other value to compare.
Returns:
bool: Whether `value` is less than or equal to `other`.
Example:
>>> lte(5, 3)
False
>>> lte(3, 5)
True
>>> lte(5, 5)
True
.. versionadded:: 3.3.0
"""
return value <= other
def in_range(value, start=0, end=None):
"""Checks if `value` is between `start` and up to but not including `end`.
If `end` is not specified it defaults to `start` with `start` becoming
``0``.
Args:
value (int|float): Number to check.
start (int|float, optional): Start of range inclusive. Defaults to
``0``.
end (int|float, optional): End of range exclusive. Defaults to `start`.
Returns:
bool: Whether `value` is in range.
Example:
>>> in_range(2, 4)
True
>>> in_range(4, 2)
False
>>> in_range(2, 1, 3)
True
>>> in_range(3, 1, 2)
False
>>> in_range(2.5, 3.5)
True
>>> in_range(3.5, 2.5)
False
.. versionadded:: 3.1.0
"""
if not is_number(value):
return False
if not is_number(start):
start = 0
if end is None:
end = start
start = 0
elif not is_number(end):
end = 0
return start <= value < end
def is_associative(value):
"""Checks if `value` is an associative object meaning that it can be
accessed via an index or key
Args:
value (mixed): Value to check.
Returns:
bool: Whether `value` is associative.
Example:
>>> is_associative([])
True
>>> is_associative({})
True
>>> is_associative(1)
False
>>> is_associative(True)
False
.. versionadded:: 2.0.0
"""
return hasattr(value, '__getitem__')
def is_blank(text):
r"""Checks if `text` contains only whitespace characters.
Args:
text (str): String to test.
Returns:
bool: Whether `text` is blank.
Example:
>>> is_blank('')
True
>>> is_blank(' \r\n ')
True
>>> is_blank(False)
False
.. versionadded:: 3.0.0
"""
try:
ret = bool(re.match(r'^(\s+)?$', text))
except TypeError:
ret = False
return ret
def is_boolean(value):
"""Checks if `value` is a boolean value.
Args:
value (mixed): Value to check.
Returns:
bool: Whether `value` is a boolean.
Example:
>>> is_boolean(True)
True
>>> is_boolean(False)
True
>>> is_boolean(0)
False
.. versionadded:: 1.0.0
.. versionchanged:: 3.0.0
Added ``is_bool`` as alias.
.. versionchanged:: 4.0.0
Removed alias ``is_bool``.
"""
return isinstance(value, bool)
def is_builtin(value):
"""Checks if `value` is a Python builtin function or method.
Args:
value (function): Value to check.
Returns:
bool: Whether `value` is a Python builtin function or method.
Example:
>>> is_builtin(1)
True
>>> is_builtin(list)
True
>>> is_builtin('foo')
False
.. versionadded:: 3.0.0
.. versionchanged:: 4.0.0
Removed alias ``is_native``.
"""
try:
return isinstance(value, BuiltinFunctionType) or value in builtins
except TypeError: # pragma: no cover
return False
def is_date(value):
"""Check if `value` is a date object.
Args:
value (mixed): Value to check.
Returns:
bool: Whether `value` is a date object.
Example:
>>> import datetime
>>> is_date(datetime.date.today())
True
>>> is_date(datetime.datetime.today())
True
>>> is_date('2014-01-01')
False
Note:
This will also return ``True`` for datetime objects.
.. versionadded:: 1.0.0
"""
return isinstance(value, datetime.date)
def is_decreasing(value):
"""Check if `value` is monotonically decreasing.
Args:
value (list): Value to check.
Returns:
bool: Whether `value` is monotonically decreasing.
Example:
>>> is_decreasing([5, 4, 4, 3])
True
>>> is_decreasing([5, 5, 5])
True
>>> is_decreasing([5, 4, 5])
False
.. versionadded:: 2.0.0
"""
return is_monotone(value, operator.ge)
def is_dict(value):
"""Checks if `value` is a ``dict``.
Args:
value (mixed): Value to check.
Returns:
bool: Whether `value` is a ``dict``.
Example:
>>> is_dict({})
True
>>> is_dict([])
False
.. versionadded:: 1.0.0
.. versionchanged:: 3.0.0
Added :func:`is_dict` as main definition and made `is_plain_object`` an
alias.
.. versionchanged:: 4.0.0
Removed alias ``is_plain_object``.
"""
return isinstance(value, dict)
def is_empty(value):
"""Checks if `value` is empty.
Args:
value (mixed): Value to check.
Returns:
bool: Whether `value` is empty.
Example:
>>> is_empty(0)
True
>>> is_empty(1)
True
>>> is_empty(True)
True
>>> is_empty('foo')
False
>>> is_empty(None)
True
>>> is_empty({})
True
Note:
Returns ``True`` for booleans and numbers.
.. versionadded:: 1.0.0
"""
return is_boolean(value) or is_number(value) or not value
def is_equal(value, other):
"""Performs a comparison between two values to determine if they are
equivalent to each other.
Args:
value (list|dict): Object to compare.
other (list|dict): Object to compare.
Returns:
bool: Whether `value` and `other` are equal.
Example:
>>> is_equal([1, 2, 3], [1, 2, 3])
True
>>> is_equal('a', 'A')
False
.. versionadded:: 1.0.0
.. versionchanged:: 4.0.0
Removed :attr:`iteratee` from :func:`is_equal` and added it in
:func:`is_equal_with`.
"""
return is_equal_with(value, other, customizer=None)
def is_equal_with(value, other, customizer):
"""This method is like :func:`is_equal` except that it accepts customizer
which is invoked to compare values. A customizer is provided which will be
executed to compare values. If the customizer returns ``None``, comparisons
will be handled by the method instead. The customizer is invoked with two
arguments: ``(value, other)``.
Args:
value (list|dict): Object to compare.
other (list|dict): Object to compare.
customizer (mixed, optional): Customizer used to compare values from
`value` and `other`.
Returns:
bool: Whether `value` and `other` are equal.
Example:
>>> is_equal_with([1, 2, 3], [1, 2, 3], None)
True
>>> is_equal_with('a', 'A', None)
False
>>> is_equal_with('a', 'A', lambda a, b: a.lower() == b.lower())
True
.. versionadded:: 4.0.0
"""
# If customizer provided, use it for comparision.
equal = customizer(value, other) if callable(customizer) else None
# Return customizer results if anything but None.
if equal is not None:
pass
elif (callable(customizer) and
type(value) is type(other) and
isinstance(value, (list, dict)) and
isinstance(other, (list, dict)) and
len(value) == len(other)):
# Walk a/b to determine equality using customizer.
for key, value in iterator(value):
if pyd.has(other, key):
equal = is_equal_with(value, other[key], customizer)
else:
equal = False
if not equal:
break
else:
# Use basic == comparision.
equal = value == other
return equal
def is_error(value):
"""Checks if `value` is an ``Exception``.
Args:
value (mixed): Value to check.
Returns:
bool: Whether `value` is an exception.
Example:
>>> is_error(Exception())
True
>>> is_error(Exception)
False
>>> is_error(None)
False
.. versionadded:: 1.1.0
"""
return isinstance(value, Exception)
def is_even(value):
"""Checks if `value` is even.
Args:
value (mixed): Value to check.
Returns:
bool: Whether `value` is even.
Example:
>>> is_even(2)
True
>>> is_even(3)
False
>>> is_even(False)
False
.. versionadded:: 2.0.0
"""
return is_number(value) and value % 2 == 0
def is_float(value):
"""Checks if `value` is a float.
Args:
value (mixed): Value to check.
Returns:
bool: Whether `value` is a float.
Example:
>>> is_float(1.0)
True
>>> is_float(1)
False
.. versionadded:: 2.0.0
"""
return isinstance(value, float)
def is_function(value):
"""Checks if `value` is a function.
Args:
value (mixed): Value to check.
Returns:
bool: Whether `value` is callable.
Example:
>>> is_function(list)
True
>>> is_function(lambda: True)
True
>>> is_function(1)
False
.. versionadded:: 1.0.0
"""
return callable(value)
def is_increasing(value):
"""Check if `value` is monotonically increasing.
Args:
value (list): Value to check.
Returns:
bool: Whether `value` is monotonically increasing.
Example:
>>> is_increasing([1, 3, 5])
True
>>> is_increasing([1, 1, 2, 3, 3])
True
>>> is_increasing([5, 5, 5])
True
>>> is_increasing([1, 2, 4, 3])
False
.. versionadded:: 2.0.0
"""
return is_monotone(value, operator.le)
def is_indexed(value):
"""Checks if `value` is integer indexed, i.e., ``list``, ``str`` or
``tuple``.
Args:
value (mixed): Value to check.
Returns:
bool: Whether `value` is integer indexed.
Example:
>>> is_indexed('')
True
>>> is_indexed([])
True
>>> is_indexed(())
True
>>> is_indexed({})
False
.. versionadded:: 2.0.0
.. versionchanged:: 3.0.0
Return ``True`` for tuples.
"""
return isinstance(value, (list, tuple, string_types))
def is_instance_of(value, types):
"""Checks if `value` is an instance of `types`.
Args:
value (mixed): Value to check.
types (mixed): Types to check against. Pass as ``tuple`` to check if
`value` is one of multiple types.
Returns:
bool: Whether `value` is an instance of `types`.
Example:
>>> is_instance_of({}, dict)
True
>>> is_instance_of({}, list)
False
.. versionadded:: 2.0.0
"""
return isinstance(value, types)
def is_integer(value):
"""Checks if `value` is a integer.
Args:
value (mixed): Value to check.
Returns:
bool: Whether `value` is an integer.
Example:
>>> is_integer(1)
True
>>> is_integer(1.0)
False
>>> is_integer(True)
False
.. versionadded:: 2.0.0
.. versionchanged:: 3.0.0
Added ``is_int`` as alias.
.. versionchanged:: 4.0.0
Removed alias ``is_int``.
"""
return is_number(value) and isinstance(value, integer_types)
def is_iterable(value):
"""Checks if `value` is an iterable.
Args:
value (mixed): Value to check.
Returns:
bool: Whether `value` is an iterable.
Example:
>>> is_iterable([])
True
>>> is_iterable({})
True
>>> is_iterable(())
True
>>> is_iterable(5)
False
>>> is_iterable(True)
False
.. versionadded:: 3.3.0
"""
try:
iter(value)
except TypeError:
return False
else:
return True
def is_json(value):
"""Checks if `value` is a valid JSON string.
Args:
value (mixed): Value to check.
Returns:
bool: Whether `value` is JSON.
Example:
>>> is_json({})
False
>>> is_json('{}')
True
>>> is_json({"hello": 1, "world": 2})
False
>>> is_json('{"hello": 1, "world": 2}')
True
.. versionadded:: 2.0.0
"""
try:
json.loads(value)
return True
except Exception: # pylint: disable=broad-except
return False
def is_list(value):
"""Checks if `value` is a list.
Args:
value (mixed): Value to check.
Returns:
bool: Whether `value` is a list.
Example:
>>> is_list([])
True
>>> is_list({})
False
>>> is_list(())
False
.. versionadded:: 1.0.0
"""
return isinstance(value, list)
def is_match(obj, source):
"""Performs a partial deep comparison between `obj` and `source` to
determine if `obj` contains equivalent property values.
Args:
obj (list|dict): Object to compare.
source (list|dict): Object of property values to match.
Returns:
bool: Whether `obj` is a match or not.
Example:
>>> is_match({'a': 1, 'b': 2}, {'b': 2})
True
>>> is_match({'a': 1, 'b': 2}, {'b': 3})
False
>>> is_match({'a': [{'b': [{'c': 3, 'd': 4}]}]},\
{'a': [{'b': [{'d': 4}]}]})
True
.. versionadded:: 3.0.0
.. versionchanged:: 3.2.0
Don't compare `obj` and `source` using ``type``. Use ``isinstance``
exclusively.
.. versionchanged:: 4.0.0
Move `iteratee` argument to :func:`is_match_with`.
"""
return is_match_with(obj, source)
def is_match_with(obj, source, customizer=None,
_key=NoValue, _obj=NoValue, _source=NoValue):
"""This method is like :func:`is_match` except that it accepts customizer
which is invoked to compare values. If customizer returns ``None``,
comparisons are handled by the method instead. The customizer is invoked
with five arguments: ``(obj_value, src_value, index|key, obj, source)``.
Args:
obj (list|dict): Object to compare.
source (list|dict): Object of property values to match.
customizer (mixed, optional): Customizer used to compare values from
`obj` and `source`.
Returns:
bool: Whether `obj` is a match or not.
Example:
>>> is_greeting = lambda val: val in ('hello', 'hi')
>>> customizer = lambda ov, sv: is_greeting(ov) and is_greeting(sv)
>>> obj = {'greeting': 'hello'}
>>> src = {'greeting': 'hi'}
>>> is_match_with(obj, src, customizer)
True
.. versionadded:: 4.0.0
"""
if _obj is NoValue:
_obj = obj
if _source is NoValue:
_source = source
if not callable(customizer):
def cbk(obj_value, src_value):
return obj_value == src_value
cbk._argcount = 2
else:
cbk = customizer
if (isinstance(obj, dict) and isinstance(source, dict) or
isinstance(obj, list) and isinstance(source, list) or
isinstance(obj, tuple) and isinstance(source, tuple)):
# Set equal to True if source is empty, otherwise, False and then allow
# deep comparison to determine equality.
equal = not source
# Walk a/b to determine equality.
for key, value in iterator(source):
try:
equal = is_match_with(obj[key], value, cbk,
_key=key, _obj=_obj, _source=_source)
except Exception: # pylint: disable=broad-except
equal = False
if not equal:
break
else:
equal = callit(cbk, obj, source, _key, _obj, _source)
return equal
def is_monotone(value, op):
"""Checks if `value` is monotonic when `operator` used for comparison.
Args:
value (list): Value to check.
op (function): Operation to used for comparison.
Returns:
bool: Whether `value` is monotone.
Example:
>>> is_monotone([1, 1, 2, 3], operator.le)
True
>>> is_monotone([1, 1, 2, 3], operator.lt)
False
.. versionadded:: 2.0.0
"""
if not is_list(value):
value = [value]
search = (False for x, y in izip(value, islice(value, 1, None))
if not op(x, y))
return next(search, True)
def is_nan(value):
"""Checks if `value` is not a number.
Args:
value (mixed): Value to check.
Returns:
bool: Whether `value` is not a number.
Example:
>>> is_nan('a')
True
>>> is_nan(1)
False
>>> is_nan(1.0)
False
.. versionadded:: 1.0.0
"""
return not is_number(value)
def is_negative(value):
"""Checks if `value` is negative.
Args:
value (mixed): Value to check.
Returns:
bool: Whether `value` is negative.
Example:
>>> is_negative(-1)
True
>>> is_negative(0)
False
>>> is_negative(1)
False
.. versionadded:: 2.0.0
"""
return is_number(value) and value < 0