Repository navigation
Expand file tree
/
Copy pathutilities.py
More file actions
1540 lines (1121 loc) · 37.4 KB
/
Copy pathutilities.py
File metadata and controls
1540 lines (1121 loc) · 37.4 KB
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
"""
Utility functions.
.. versionadded:: 1.0.0
"""
from collections import namedtuple
from datetime import datetime
from functools import partial, wraps
import math
from random import randint, uniform
import re
import time
import typing as t
from typing_extensions import Literal, ParamSpec, Protocol, Type
import pydash as pyd
from .helpers import NUMBER_TYPES, UNSET, base_get, callit, getargcount, iterator
from .types import PathT
__all__ = (
"attempt",
"cond",
"conforms",
"conforms_to",
"constant",
"default_to",
"default_to_any",
"identity",
"iteratee",
"matches",
"matches_property",
"memoize",
"method",
"method_of",
"noop",
"nth_arg",
"now",
"over",
"over_every",
"over_some",
"properties",
"property_",
"property_of",
"random",
"range_",
"range_right",
"result",
"retry",
"stub_list",
"stub_dict",
"stub_false",
"stub_string",
"stub_true",
"times",
"to_path",
"unique_id",
)
T = t.TypeVar("T")
T2 = t.TypeVar("T2")
CallableT = t.TypeVar("CallableT", bound=t.Callable)
P = ParamSpec("P")
# These regexes are used in to_path() to parse deep path strings.
# This is used to split a deep path string into dict keys or list indexes. This matches "." as
# delimiter (unless it is escaped by "//") and "[<integer>]" as delimiter while keeping the
# "[<integer>]" as an item.
RE_PATH_KEY_DELIM = re.compile(r"(?<!\\)(?:\\\\)*\.|(\[-?\d+\])")
# Matches on path strings like "[<integer>]". This is used to test whether a path string part is a
# list index.
RE_PATH_LIST_INDEX = re.compile(r"^\[-?\d+\]$")
ID_COUNTER = 0
PathToken = namedtuple("PathToken", ["key", "default_factory"])
def attempt(func: t.Callable[P, T], *args: "P.args", **kwargs: "P.kwargs") -> t.Union[T, Exception]:
"""
Attempts to execute `func`, returning either the result or the caught error object.
Args:
func: The function to attempt.
Returns:
Returns the `func` result or error object.
Example:
>>> results = attempt(lambda x: x/0, 1)
>>> assert isinstance(results, ZeroDivisionError)
.. versionadded:: 1.1.0
"""
try:
ret = func(*args, **kwargs)
except Exception as ex:
# allow different type reassignment
ret = ex # type: ignore
return ret
@t.overload
def cond(
pairs: t.List[t.Tuple[t.Callable[P, t.Any], t.Callable[P, T]]],
*extra_pairs: t.Tuple[t.Callable[P, t.Any], t.Callable[P, T]],
) -> t.Callable[P, T]:
...
@t.overload
def cond(
pairs: t.List[t.List[t.Callable[P, t.Any]]], *extra_pairs: t.List[t.Callable[P, t.Any]]
) -> t.Callable[P, t.Any]:
...
def cond(pairs, *extra_pairs):
"""
Creates a function that iterates over `pairs` and invokes the corresponding function of the
first predicate to return truthy.
Args:
pairs: A list of predicate-function pairs.
Returns:
Returns the new composite function.
Example:
>>> func = cond([[matches({'a': 1}), constant('matches A')],\
[matches({'b': 2}), constant('matches B')],\
[stub_true, lambda value: value]])
>>> func({'a': 1, 'b': 2})
'matches A'
>>> func({'a': 0, 'b': 2})
'matches B'
>>> func({'a': 0, 'b': 0}) == {'a': 0, 'b': 0}
True
.. versionadded:: 4.0.0
.. versionchanged:: 4.2.0
Fixed missing argument passing to matched function and added support for passing in a single
list of pairs instead of just pairs as separate arguments.
"""
if extra_pairs:
pairs = [pairs] + list(extra_pairs)
for pair in pairs:
is_valid = False
try:
is_valid = len(pair) == 2
except Exception:
pass
if not is_valid:
raise ValueError("Each predicate-function pair should contain " "exactly two elements")
if not all(map(callable, pair)):
raise TypeError("Both predicate-function pair should be callable")
def _cond(*args):
for pair in pairs:
predicate, iteratee = pair
if callit(predicate, *args):
return iteratee(*args)
return _cond
@t.overload
def conforms(source: t.Dict[T, t.Callable[[T2], t.Any]]) -> t.Callable[[t.Dict[T, T2]], bool]:
...
@t.overload
def conforms(source: t.List[t.Callable[[T], t.Any]]) -> t.Callable[[t.List[T]], bool]:
...
def conforms(source: t.Union[t.List, t.Dict]) -> t.Callable:
"""
Creates a function that invokes the predicate properties of `source` with the corresponding
property values of a given object, returning ``True`` if all predicates return truthy, else
``False``.
Args:
source: The object of property predicates to conform to.
Returns:
Returns the new spec function.
Example:
>>> func = conforms({'b': lambda n: n > 1})
>>> func({'b': 2})
True
>>> func({'b': 0})
False
>>> func = conforms([lambda n: n > 1, lambda n: n == 0])
>>> func([2, 0])
True
>>> func([0, 0])
False
.. versionadded:: 4.0.0
"""
def _conforms(obj):
for key, predicate in iterator(source):
if not pyd.has(obj, key) or not predicate(obj[key]):
return False
return True
return _conforms
@t.overload
def conforms_to(obj: t.Dict[T, T2], source: t.Dict[T, t.Callable[[T2], t.Any]]) -> bool:
...
@t.overload
def conforms_to(obj: t.List[T], source: t.List[t.Callable[[T], t.Any]]) -> bool:
...
def conforms_to(obj, source):
"""
Checks if `obj` conforms to `source` by invoking the predicate properties of `source` with the
corresponding property values of `obj`.
Args:
obj: The object to inspect.
source: The object of property predicates to conform to.
Example:
>>> conforms_to({'b': 2}, {'b': lambda n: n > 1})
True
>>> conforms_to({'b': 0}, {'b': lambda n: n > 1})
False
>>> conforms_to([2, 0], [lambda n: n > 1, lambda n: n == 0])
True
>>> conforms_to([0, 0], [lambda n: n > 1, lambda n: n == 0])
False
.. versionadded:: 4.0.0
"""
return conforms(source)(obj)
def constant(value: T) -> t.Callable[..., T]:
"""
Creates a function that returns `value`.
Args:
value: Constant value to return.
Returns:
Function that always returns `value`.
Example:
>>> pi = constant(3.14)
>>> pi() == 3.14
True
.. versionadded:: 1.0.0
.. versionchanged:: 4.0.0
Returned function ignores arguments instead of raising exception.
"""
return partial(identity, value)
def default_to(value: t.Union[T, None], default_value: T2) -> t.Union[T, T2]:
"""
Checks `value` to determine whether a default value should be returned in its place. The
`default_value` is returned if value is None.
Args:
default_value: Default value passed in by the user.
Returns:
Returns `value` if :attr:`value` is given otherwise returns `default_value`.
Example:
>>> default_to(1, 10)
1
>>> default_to(None, 10)
10
.. versionadded:: 4.0.0
"""
return default_to_any(value, default_value)
@t.overload
def default_to_any(value: None, *default_values: None) -> None:
...
@t.overload
def default_to_any(
value: t.Union[T, None],
default_value1: None,
default_value2: T2,
) -> t.Union[T, T2]:
...
@t.overload
def default_to_any(
value: t.Union[T, None],
default_value1: None,
default_value2: None,
default_value3: T2,
) -> t.Union[T, T2]:
...
@t.overload
def default_to_any(
value: t.Union[T, None],
default_value1: None,
default_value2: None,
default_value3: None,
default_value4: T2,
) -> t.Union[T, T2]:
...
@t.overload
def default_to_any(
value: t.Union[T, None],
default_value1: None,
default_value2: None,
default_value3: None,
default_value4: None,
default_value5: T2,
) -> t.Union[T, T2]:
...
@t.overload
def default_to_any(value: t.Union[T, None], *default_values: T2) -> t.Union[T, T2]:
...
def default_to_any(value, *default_values):
"""
Checks `value` to determine whether a default value should be returned in its place. The first
item that is not None of the `default_values` is returned.
Args:
value: Value passed in by the user.
*default_values: Default values passed in by the user.
Returns:
Returns `value` if :attr:`value` is given otherwise returns the first not None value
of `default_values`.
Example:
>>> default_to_any(1, 10, 20)
1
>>> default_to_any(None, 10, 20)
10
>>> default_to_any(None, None, 20)
20
.. versionadded:: 4.9.0
"""
values = (value,) + default_values
for val in values:
if val is not None:
return val
@t.overload
def identity(arg: T, *args: t.Any) -> T:
...
@t.overload
def identity(arg: None = None, *args: t.Any) -> None:
...
def identity(arg=None, *args):
"""
Return the first argument provided to it.
Args:
*args: Arguments.
Returns:
First argument or ``None``.
Example:
>>> identity(1)
1
>>> identity(1, 2, 3)
1
>>> identity() is None
True
.. versionadded:: 1.0.0
"""
return arg
@t.overload
def iteratee(func: t.Callable[P, T]) -> t.Callable[P, T]:
...
@t.overload
def iteratee(func: t.Any) -> t.Callable:
...
def iteratee(func):
"""
Return a pydash style iteratee. If `func` is a property name the created iteratee will return
the property value for a given element. If `func` is an object the created iteratee will return
``True`` for elements that contain the equivalent object properties, otherwise it will return
``False``.
Args:
func: Object to create iteratee function from.
Returns:
Iteratee function.
Example:
>>> get_data = iteratee('data')
>>> get_data({'data': [1, 2, 3]})
[1, 2, 3]
>>> is_active = iteratee({'active': True})
>>> is_active({'active': True})
True
>>> is_active({'active': 0})
False
>>> iteratee(['a', 5])({'a': 5})
True
>>> iteratee(['a.b'])({'a.b': 5})
5
>>> iteratee('a.b')({'a': {'b': 5}})
5
>>> iteratee(('a', ['c', 'd', 'e']))({'a': 1, 'c': {'d': {'e': 3}}})
[1, 3]
>>> iteratee(lambda a, b: a + b)(1, 2)
3
>>> ident = iteratee(None)
>>> ident('a')
'a'
>>> ident(1, 2, 3)
1
.. versionadded:: 1.0.0
.. versionchanged:: 2.0.0
Renamed ``create_iteratee()`` to :func:`iteratee`.
.. versionchanged:: 3.0.0
Made pluck style iteratee support deep property access.
.. versionchanged:: 3.1.0
- Added support for shallow pluck style property access via single item list/tuple.
- Added support for matches property style iteratee via two item list/tuple.
.. versionchanged:: 4.0.0
Removed alias ``callback``.
.. versionchanged:: 4.1.0
Return :func:`properties` callback when `func` is a ``tuple``.
"""
if callable(func):
cbk = func
else:
if isinstance(func, int):
func = str(func)
if isinstance(func, str):
cbk = property_(func)
elif isinstance(func, list) and len(func) == 1:
cbk = property_(func)
elif isinstance(func, list) and len(func) > 1:
cbk = matches_property(*func[:2])
elif isinstance(func, tuple):
cbk = properties(*func)
elif isinstance(func, dict):
cbk = matches(func)
else:
cbk = identity
# Optimize iteratee by specifying the exact number of arguments the iteratee takes so that
# arg inspection (costly process) can be skipped in helpers.callit().
cbk._argcount = 1
return cbk
def matches(source: t.Any) -> t.Callable[[t.Any], bool]:
"""
Creates a matches-style predicate function which performs a deep comparison between a given
object and the `source` object, returning ``True`` if the given object has equivalent property
values, else ``False``.
Args:
source: Source object used for comparision.
Returns:
Function that compares an object to `source` and returns whether the two objects
contain the same items.
Example:
>>> matches({'a': {'b': 2}})({'a': {'b': 2, 'c':3}})
True
>>> matches({'a': 1})({'b': 2, 'a': 1})
True
>>> matches({'a': 1})({'b': 2, 'a': 2})
False
.. versionadded:: 1.0.0
.. versionchanged:: 3.0.0
Use :func:`pydash.predicates.is_match` as matching function.
"""
return lambda obj: pyd.is_match(obj, source)
def matches_property(key: t.Any, value: t.Any) -> t.Callable[[t.Any], bool]:
"""
Creates a function that compares the property value of `key` on a given object to `value`.
Args:
key: Object key to match against.
value: Value to compare to.
Returns:
Function that compares `value` to an object's `key` and returns whether they are
equal.
Example:
>>> matches_property('a', 1)({'a': 1, 'b': 2})
True
>>> matches_property(0, 1)([1, 2, 3])
True
>>> matches_property('a', 2)({'a': 1, 'b': 2})
False
.. versionadded:: 3.1.0
"""
prop_accessor = property_(key)
return lambda obj: matches(value)(prop_accessor(obj))
class MemoizedFunc(Protocol[P, T, T2]):
cache: t.Dict[T2, T]
def __call__(self, *args: P.args, **kwargs: P.kwargs) -> T:
... # pragma: no cover
@t.overload
def memoize(func: t.Callable[P, T], resolver: None = None) -> MemoizedFunc[P, T, str]:
...
@t.overload
def memoize(
func: t.Callable[P, T], resolver: t.Union[t.Callable[P, T2], None] = None
) -> MemoizedFunc[P, T, T2]:
...
def memoize(func, resolver=None):
"""
Creates a function that memoizes the result of `func`. If `resolver` is provided it will be used
to determine the cache key for storing the result based on the arguments provided to the
memoized function. By default, all arguments provided to the memoized function are used as the
cache key. The result cache is exposed as the cache property on the memoized function.
Args:
func: Function to memoize.
resolver: Function that returns the cache key to use.
Returns:
Memoized function.
Example:
>>> ident = memoize(identity)
>>> ident(1)
1
>>> ident.cache['(1,){}'] == 1
True
>>> ident(1, 2, 3)
1
>>> ident.cache['(1, 2, 3){}'] == 1
True
.. versionadded:: 1.0.0
"""
def memoized(*args: P.args, **kwargs: P.kwargs):
if resolver:
key = resolver(*args, **kwargs)
else:
key = f"{args}{kwargs}"
if key not in memoized.cache: # type: ignore
memoized.cache[key] = func(*args, **kwargs) # type:ignore
return memoized.cache[key] # type: ignore
memoized.cache = {}
return memoized
def method(path: PathT, *args: t.Any, **kwargs: t.Any) -> t.Callable[..., t.Any]:
"""
Creates a function that invokes the method at `path` on a given object. Any additional arguments
are provided to the invoked method.
Args:
path: Object path of method to invoke.
*args: Global arguments to apply to method when invoked.
**kwargs: Global keyword argument to apply to method when invoked.
Returns:
Function that invokes method located at path for object.
Example:
>>> obj = {'a': {'b': [None, lambda x: x]}}
>>> echo = method('a.b.1')
>>> echo(obj, 1) == 1
True
>>> echo(obj, 'one') == 'one'
True
.. versionadded:: 3.3.0
"""
def _method(obj, *_args, **_kwargs):
func = pyd.partial(pyd.get(obj, path), *args, **kwargs)
return func(*_args, **_kwargs)
return _method
def method_of(obj: t.Any, *args: t.Any, **kwargs: t.Any) -> t.Callable[..., t.Any]:
"""
The opposite of :func:`method`. This method creates a function that invokes the method at a
given path on object. Any additional arguments are provided to the invoked method.
Args:
obj: The object to query.
*args: Global arguments to apply to method when invoked.
**kwargs: Global keyword argument to apply to method when invoked.
Returns:
Function that invokes method located at path for object.
Example:
>>> obj = {'a': {'b': [None, lambda x: x]}}
>>> dispatch = method_of(obj)
>>> dispatch('a.b.1', 1) == 1
True
>>> dispatch('a.b.1', 'one') == 'one'
True
.. versionadded:: 3.3.0
"""
def _method_of(path, *_args, **_kwargs):
func = pyd.partial(pyd.get(obj, path), *args, **kwargs)
return func(*_args, **_kwargs)
return _method_of
def noop(*args: t.Any, **kwargs: t.Any) -> None: # pylint: disable=unused-argument
"""
A no-operation function.
.. versionadded:: 1.0.0
"""
pass
def nth_arg(pos: int = 0) -> t.Callable[..., t.Any]:
"""
Creates a function that gets the argument at index n. If n is negative, the nth argument from
the end is returned.
Args:
pos: The index of the argument to return.
Returns:
Returns the new pass-thru function.
Example:
>>> func = nth_arg(1)
>>> func(11, 22, 33, 44)
22
>>> func = nth_arg(-1)
>>> func(11, 22, 33, 44)
44
.. versionadded:: 4.0.0
"""
def _nth_arg(*args):
try:
position = math.ceil(float(pos))
except ValueError:
position = 0
return pyd.get(args, position)
return _nth_arg
def now() -> int:
"""
Return the number of milliseconds that have elapsed since the Unix epoch (1 January 1970
00:00:00 UTC).
Returns:
Milliseconds since Unix epoch.
.. versionadded:: 1.0.0
.. versionchanged:: 3.0.0
Use ``datetime`` module for calculating elapsed time.
"""
epoch = datetime.utcfromtimestamp(0)
delta = datetime.utcnow() - epoch
if hasattr(delta, "total_seconds"):
seconds = delta.total_seconds()
else: # pragma: no cover
# PY26
seconds = (
delta.microseconds + (delta.seconds + delta.days * 24 * 3600) * 10**6
) / 10**6
return int(seconds * 1000)
def over(funcs: t.Iterable[t.Callable[P, T]]) -> t.Callable[P, t.List[T]]:
"""
Creates a function that invokes all functions in `funcs` with the arguments it receives and
returns their results.
Args:
funcs: List of functions to be invoked.
Returns:
Returns the new pass-thru function.
Example:
>>> func = over([max, min])
>>> func(1, 2, 3, 4)
[4, 1]
.. versionadded:: 4.0.0
"""
def _over(*args: P.args, **kwargs: P.kwargs) -> t.List[T]:
return [func(*args, **kwargs) for func in funcs]
return _over
def over_every(funcs: t.Iterable[t.Callable[P, t.Any]]) -> t.Callable[P, bool]:
"""
Creates a function that checks if all the functions in `funcs` return truthy when invoked with
the arguments it receives.
Args:
funcs: List of functions to be invoked.
Returns:
Returns the new pass-thru function.
Example:
>>> func = over_every([bool, lambda x: x is not None])
>>> func(1)
True
.. versionadded:: 4.0.0
"""
def _over_every(*args: P.args, **kwargs: P.kwargs) -> bool:
return all(func(*args, **kwargs) for func in funcs)
return _over_every
def over_some(funcs: t.Iterable[t.Callable[P, t.Any]]) -> t.Callable[P, bool]:
"""
Creates a function that checks if any of the functions in `funcs` return truthy when invoked
with the arguments it receives.
Args:
funcs: List of functions to be invoked.
Returns:
Returns the new pass-thru function.
Example:
>>> func = over_some([bool, lambda x: x is None])
>>> func(1)
True
.. versionadded:: 4.0.0
"""
def _over_some(*args: P.args, **kwargs: P.kwargs) -> bool:
return any(func(*args, **kwargs) for func in funcs)
return _over_some
def property_(path: PathT) -> t.Callable[[t.Any], t.Any]:
"""
Creates a function that returns the value at path of a given object.
Args:
path: Path value to fetch from object.
Returns:
Function that returns object's path value.
Example:
>>> get_data = property_('data')
>>> get_data({'data': 1})
1
>>> get_data({}) is None
True
>>> get_first = property_(0)
>>> get_first([1, 2, 3])
1
.. versionadded:: 1.0.0
.. versionchanged:: 4.0.1
Made property accessor work with deep path strings.
"""
return lambda obj: pyd.get(obj, path)
def properties(*paths: t.Any) -> t.Callable[[t.Any], t.Any]:
"""
Like :func:`property_` except that it returns a list of values at each path in `paths`.
Args:
*path: Path values to fetch from object.
Returns:
Function that returns object's path value.
Example:
>>> getter = properties('a', 'b', ['c', 'd', 'e'])
>>> getter({'a': 1, 'b': 2, 'c': {'d': {'e': 3}}})
[1, 2, 3]
.. versionadded:: 4.1.0
"""
return lambda obj: [getter(obj) for getter in (pyd.property_(path) for path in paths)]
def property_of(obj: t.Any) -> t.Callable[[PathT], t.Any]:
"""
The inverse of :func:`property_`. This method creates a function that returns the key value of a
given key on `obj`.
Args:
obj: Object to fetch values from.
Returns:
Function that returns object's key value.
Example:
>>> getter = property_of({'a': 1, 'b': 2, 'c': 3})
>>> getter('a')
1
>>> getter('b')
2
>>> getter('x') is None
True
.. versionadded:: 3.0.0
.. versionchanged:: 4.0.0
Removed alias ``prop_of``.
"""
return lambda key: pyd.get(obj, key)
@t.overload
def random(start: int = 0, stop: int = 1, *, floating: Literal[False] = False) -> int:
...
@t.overload
def random(start: float, stop: int = 1, floating: bool = False) -> float:
...
@t.overload
def random(start: int = 0, *, stop: float, floating: bool = False) -> float:
...
@t.overload
def random(start: float, stop: float, floating: bool = False) -> float:
...
@t.overload
def random(
start: t.Union[float, int] = 0, stop: t.Union[float, int] = 1, *, floating: Literal[True]
) -> float:
...
def random(start: t.Union[float, int] = 0, stop: t.Union[float, int] = 1, floating: bool = False):
"""
Produces a random number between `start` and `stop` (inclusive). If only one argument is
provided a number between 0 and the given number will be returned. If floating is truthy or
either `start` or `stop` are floats a floating-point number will be returned instead of an
integer.
Args:
start: Minimum value.
stop: Maximum value.
floating: Whether to force random value to ``float``. Defaults to
``False``.
Returns:
Random value.
Example:
>>> 0 <= random() <= 1
True
>>> 5 <= random(5, 10) <= 10
True
>>> isinstance(random(floating=True), float)
True
.. versionadded:: 1.0.0
"""
floating = isinstance(start, float) or isinstance(stop, float) or floating is True
if stop < start:
stop, start = start, stop
if floating:
rnd = uniform(start, stop)
else:
rnd = randint(start, stop) # type: ignore
return rnd
@t.overload
def range_(stop: int) -> t.Generator[int, None, None]: