0
# Utilities Module
1
2
The Utilities module provides 38 general utility functions and helpers for common programming tasks. These functions include function creation utilities, value generation, random operations, conditional logic, and various helper functions.
3
4
## Function Creation Utilities
5
6
### constant
7
8
```python { .api }
9
def constant(value: Any) -> Callable
10
```
11
12
Creates a function that returns `value`.
13
14
**Parameters:**
15
- `value` (`Any`): Value to return from new function.
16
17
**Returns:**
18
- `Callable`: New constant function.
19
20
**Example:**
21
```python { .api }
22
from pydash import constant
23
24
always_true = constant(True)
25
always_true() # True
26
always_true(1, 2, 3) # True (ignores arguments)
27
28
get_pi = constant(3.14159)
29
get_pi() # 3.14159
30
```
31
32
### identity
33
34
```python { .api }
35
def identity(value: Any) -> Any
36
```
37
38
Returns the first argument it receives.
39
40
**Parameters:**
41
- `value` (`Any`): Any value.
42
43
**Returns:**
44
- `Any`: `value`.
45
46
**Example:**
47
```python { .api }
48
from pydash import identity
49
50
identity('hello') # 'hello'
51
identity([1, 2, 3]) # [1, 2, 3]
52
53
# Useful as a default function
54
list(map(identity, [1, 2, 3])) # [1, 2, 3]
55
```
56
57
### iteratee
58
59
```python { .api }
60
def iteratee(func: Any = None) -> Callable
61
```
62
63
Creates an iteratee function from `func`. This function is used internally by many pydash methods.
64
65
**Parameters:**
66
- `func` (`Any`, optional): Value to convert to an iteratee.
67
68
**Returns:**
69
- `Callable`: New iteratee function.
70
71
**Example:**
72
```python { .api }
73
from pydash import iteratee
74
75
# Function iteratee
76
func_iter = iteratee(lambda x: x * 2)
77
func_iter(5) # 10
78
79
# Property iteratee
80
prop_iter = iteratee('name')
81
prop_iter({'name': 'John'}) # 'John'
82
83
# Matches iteratee
84
match_iter = iteratee({'age': 25})
85
match_iter({'name': 'John', 'age': 25}) # True
86
```
87
88
### matches
89
90
```python { .api }
91
def matches(source: Any) -> Callable
92
```
93
94
Creates a function that performs a partial deep comparison between a given object and `source`, returning `True` if the given object has equivalent property values, else `False`.
95
96
**Parameters:**
97
- `source` (`Any`): Object of property values to match.
98
99
**Returns:**
100
- `Callable`: New predicate function.
101
102
**Example:**
103
```python { .api }
104
from pydash import matches, filter_
105
106
is_user_active = matches({'active': True, 'status': 'online'})
107
108
users = [
109
{'name': 'John', 'active': True, 'status': 'online'},
110
{'name': 'Jane', 'active': False, 'status': 'offline'},
111
{'name': 'Bob', 'active': True, 'status': 'online'}
112
]
113
114
active_users = filter_(users, is_user_active)
115
# [{'name': 'John', 'active': True, 'status': 'online'},
116
# {'name': 'Bob', 'active': True, 'status': 'online'}]
117
```
118
119
### matches_property
120
121
```python { .api }
122
def matches_property(path: Union[str, List], src_value: Any) -> Callable
123
```
124
125
Creates a function that compares the value at `path` of a given object to `src_value`.
126
127
**Parameters:**
128
- `path` (`Union[str, List]`): Path of the property to get.
129
- `src_value` (`Any`): Value to match.
130
131
**Returns:**
132
- `Callable`: New predicate function.
133
134
**Example:**
135
```python { .api }
136
from pydash import matches_property, filter_
137
138
is_adult = matches_property('age', 18)
139
has_admin_role = matches_property('roles[0]', 'admin')
140
141
users = [
142
{'name': 'John', 'age': 25, 'roles': ['admin', 'user']},
143
{'name': 'Jane', 'age': 17, 'roles': ['user']},
144
{'name': 'Bob', 'age': 30, 'roles': ['user']}
145
]
146
147
adults = filter_(users, lambda u: u['age'] >= 18)
148
admins = filter_(users, has_admin_role)
149
```
150
151
### method
152
153
```python { .api }
154
def method(path: Union[str, List], *args: Any, **kwargs: Any) -> Callable
155
```
156
157
Creates a function that invokes the method at `path` of a given object.
158
159
**Parameters:**
160
- `path` (`Union[str, List]`): Path of the method to invoke.
161
- `args` (`*Any`): Arguments to invoke the method with.
162
- `kwargs` (`**Any`): Keyword arguments to invoke the method with.
163
164
**Returns:**
165
- `Callable`: New invoker function.
166
167
**Example:**
168
```python { .api }
169
from pydash import method, map_
170
171
upper_method = method('upper')
172
split_comma = method('split', ',')
173
174
strings = ['hello', 'world', 'foo,bar,baz']
175
map_(strings[:2], upper_method) # ['HELLO', 'WORLD']
176
split_comma('a,b,c') # ['a', 'b', 'c']
177
```
178
179
### method_of
180
181
```python { .api }
182
def method_of(obj: Any, *args: Any, **kwargs: Any) -> Callable
183
```
184
185
Creates a function that invokes the method at a given path of `obj`.
186
187
**Parameters:**
188
- `obj` (`Any`): Object to query.
189
- `args` (`*Any`): Arguments to invoke the method with.
190
- `kwargs` (`**Any`): Keyword arguments to invoke the method with.
191
192
**Returns:**
193
- `Callable`: New invoker function.
194
195
**Example:**
196
```python { .api }
197
from pydash import method_of
198
199
string_obj = 'hello world'
200
get_char = method_of(string_obj)
201
202
get_char('__getitem__', 0) # 'h'
203
get_char('upper') # 'HELLO WORLD'
204
```
205
206
### noop
207
208
```python { .api }
209
def noop(*args: Any, **kwargs: Any) -> None
210
```
211
212
A function that returns `None` regardless of the arguments it receives.
213
214
**Parameters:**
215
- `args` (`*Any`): Any arguments (ignored).
216
- `kwargs` (`**Any`): Any keyword arguments (ignored).
217
218
**Returns:**
219
- `None`: Always returns `None`.
220
221
**Example:**
222
```python { .api }
223
from pydash import noop
224
225
noop() # None
226
noop(1, 2, 3) # None
227
noop(a=1, b=2) # None
228
229
# Useful as a default callback
230
def process_data(data, callback=noop):
231
result = transform(data)
232
callback(result) # Safe to call even if no callback provided
233
return result
234
```
235
236
### property_
237
238
```python { .api }
239
def property_(path: Union[str, List]) -> Callable
240
```
241
242
Creates a function that returns the value at `path` of a given object.
243
244
**Parameters:**
245
- `path` (`Union[str, List]`): Path of the property to get.
246
247
**Returns:**
248
- `Callable`: New accessor function.
249
250
**Example:**
251
```python { .api }
252
from pydash import property_, map_
253
254
get_name = property_('name')
255
get_nested = property_('user.profile.email')
256
257
users = [
258
{'name': 'John', 'age': 25},
259
{'name': 'Jane', 'age': 30}
260
]
261
262
names = map_(users, get_name) # ['John', 'Jane']
263
264
# With nested properties
265
data = {'user': {'profile': {'email': 'john@example.com'}}}
266
get_nested(data) # 'john@example.com'
267
```
268
269
### property_of
270
271
```python { .api }
272
def property_of(obj: Any) -> Callable
273
```
274
275
Creates a function that returns the value at a given path of `obj`.
276
277
**Parameters:**
278
- `obj` (`Any`): Object to query.
279
280
**Returns:**
281
- `Callable`: New accessor function.
282
283
**Example:**
284
```python { .api }
285
from pydash import property_of
286
287
user = {'name': 'John', 'profile': {'email': 'john@example.com'}}
288
get_from_user = property_of(user)
289
290
get_from_user('name') # 'John'
291
get_from_user('profile.email') # 'john@example.com'
292
```
293
294
## Value Generation and Random Functions
295
296
### now
297
298
```python { .api }
299
def now() -> int
300
```
301
302
Returns the timestamp in milliseconds of the current time.
303
304
**Parameters:**
305
None
306
307
**Returns:**
308
- `int`: Current timestamp in milliseconds.
309
310
**Example:**
311
```python { .api }
312
from pydash import now
313
314
timestamp = now() # e.g., 1634567890123
315
```
316
317
### random
318
319
```python { .api }
320
def random(lower: Union[int, float] = 0, upper: Union[int, float] = 1, floating: bool = None) -> Union[int, float]
321
```
322
323
Produces a random number between the inclusive `lower` and `upper` bounds.
324
325
**Parameters:**
326
- `lower` (`Union[int, float]`): Lower bound. Defaults to `0`.
327
- `upper` (`Union[int, float]`): Upper bound. Defaults to `1`.
328
- `floating` (`bool`, optional): Specify returning a floating-point number.
329
330
**Returns:**
331
- `Union[int, float]`: Random number.
332
333
**Example:**
334
```python { .api }
335
from pydash import random
336
337
random(0, 5) # e.g., 3
338
random(1.2, 5.2) # e.g., 3.7
339
random(0, 1, True) # e.g., 0.8234
340
```
341
342
### range_
343
344
```python { .api }
345
def range_(start: int = 0, stop: int = None, step: int = 1) -> List[int]
346
```
347
348
Creates a list of numbers progressing from `start` up to, but not including, `stop`.
349
350
**Parameters:**
351
- `start` (`int`): Start of the range. Defaults to `0`.
352
- `stop` (`int`, optional): End of the range.
353
- `step` (`int`): Increment between numbers. Defaults to `1`.
354
355
**Returns:**
356
- `List[int]`: List of numbers.
357
358
**Example:**
359
```python { .api }
360
from pydash import range_
361
362
range_(4) # [0, 1, 2, 3]
363
range_(1, 5) # [1, 2, 3, 4]
364
range_(0, 20, 5) # [0, 5, 10, 15]
365
range_(0, -4, -1) # [0, -1, -2, -3]
366
```
367
368
### range_right
369
370
```python { .api }
371
def range_right(start: int = 0, stop: int = None, step: int = 1) -> List[int]
372
```
373
374
Like `range_` except that it populates values in descending order.
375
376
**Parameters:**
377
- `start` (`int`): Start of the range. Defaults to `0`.
378
- `stop` (`int`, optional): End of the range.
379
- `step` (`int`): Increment between numbers. Defaults to `1`.
380
381
**Returns:**
382
- `List[int]`: List of numbers in descending order.
383
384
**Example:**
385
```python { .api }
386
from pydash import range_right
387
388
range_right(4) # [3, 2, 1, 0]
389
range_right(1, 5) # [4, 3, 2, 1]
390
```
391
392
### times
393
394
```python { .api }
395
def times(n: int, iteratee: Callable = None) -> List[Any]
396
```
397
398
Invokes the iteratee `n` times, returning a list of the results of each invocation.
399
400
**Parameters:**
401
- `n` (`int`): Number of times to invoke `iteratee`.
402
- `iteratee` (`Callable`, optional): Function invoked per iteration.
403
404
**Returns:**
405
- `List[Any]`: List of results.
406
407
**Example:**
408
```python { .api }
409
from pydash import times
410
411
times(3) # [0, 1, 2]
412
times(4, lambda i: i * i) # [0, 1, 4, 9]
413
times(3, lambda: 'hello') # ['hello', 'hello', 'hello']
414
```
415
416
### unique_id
417
418
```python { .api }
419
def unique_id(prefix: str = '') -> str
420
```
421
422
Generates a unique ID. If `prefix` is provided, the ID is prefixed with it.
423
424
**Parameters:**
425
- `prefix` (`str`): Value to prefix the ID with. Defaults to `''`.
426
427
**Returns:**
428
- `str`: Unique ID.
429
430
**Example:**
431
```python { .api }
432
from pydash import unique_id
433
434
unique_id() # '1'
435
unique_id('contact_') # 'contact_2'
436
unique_id('user_') # 'user_3'
437
```
438
439
## Stub Functions
440
441
### stub_dict
442
443
```python { .api }
444
def stub_dict() -> Dict
445
```
446
447
Returns a new empty dictionary.
448
449
**Parameters:**
450
None
451
452
**Returns:**
453
- `Dict`: Empty dictionary.
454
455
**Example:**
456
```python { .api }
457
from pydash import stub_dict
458
459
stub_dict() # {}
460
```
461
462
### stub_false
463
464
```python { .api }
465
def stub_false() -> bool
466
```
467
468
Returns `False`.
469
470
**Parameters:**
471
None
472
473
**Returns:**
474
- `bool`: `False`.
475
476
**Example:**
477
```python { .api }
478
from pydash import stub_false
479
480
stub_false() # False
481
```
482
483
### stub_list
484
485
```python { .api }
486
def stub_list() -> List
487
```
488
489
Returns a new empty list.
490
491
**Parameters:**
492
None
493
494
**Returns:**
495
- `List`: Empty list.
496
497
**Example:**
498
```python { .api }
499
from pydash import stub_list
500
501
stub_list() # []
502
```
503
504
### stub_string
505
506
```python { .api }
507
def stub_string() -> str
508
```
509
510
Returns an empty string.
511
512
**Parameters:**
513
None
514
515
**Returns:**
516
- `str`: Empty string.
517
518
**Example:**
519
```python { .api }
520
from pydash import stub_string
521
522
stub_string() # ''
523
```
524
525
### stub_true
526
527
```python { .api }
528
def stub_true() -> bool
529
```
530
531
Returns `True`.
532
533
**Parameters:**
534
None
535
536
**Returns:**
537
- `bool`: `True`.
538
539
**Example:**
540
```python { .api }
541
from pydash import stub_true
542
543
stub_true() # True
544
```
545
546
## Value Testing and Conversion
547
548
### attempt
549
550
```python { .api }
551
def attempt(func: Callable, *args: Any, **kwargs: Any) -> Any
552
```
553
554
Attempts to invoke `func`, returning either the result or the caught error object.
555
556
**Parameters:**
557
- `func` (`Callable`): Function to attempt.
558
- `args` (`*Any`): Arguments to invoke `func` with.
559
- `kwargs` (`**Any`): Keyword arguments to invoke `func` with.
560
561
**Returns:**
562
- `Any`: Function result or error object.
563
564
**Example:**
565
```python { .api }
566
from pydash import attempt, is_error
567
568
# Successful execution
569
result = attempt(int, '42') # 42
570
571
# Failed execution
572
result = attempt(int, 'invalid')
573
is_error(result) # True
574
```
575
576
### default_to
577
578
```python { .api }
579
def default_to(value: Any, default_value: Any) -> Any
580
```
581
582
Checks `value` to determine whether a default value should be returned in its place. The `default_value` is returned if `value` is `None` or `NaN`.
583
584
**Parameters:**
585
- `value` (`Any`): Value to check.
586
- `default_value` (`Any`): Default value.
587
588
**Returns:**
589
- `Any`: `value` or `default_value`.
590
591
**Example:**
592
```python { .api }
593
from pydash import default_to
594
595
default_to(1, 10) # 1
596
default_to(None, 10) # 10
597
default_to(float('nan'), 10) # 10
598
```
599
600
### default_to_any
601
602
```python { .api }
603
def default_to_any(value: Any, *default_values: Any) -> Any
604
```
605
606
Like `default_to` except that it accepts multiple default values and returns the first non-nullish value.
607
608
**Parameters:**
609
- `value` (`Any`): Value to check.
610
- `default_values` (`*Any`): Default values to check.
611
612
**Returns:**
613
- `Any`: First non-nullish value.
614
615
**Example:**
616
```python { .api }
617
from pydash import default_to_any
618
619
default_to_any(None, None, 'default') # 'default'
620
default_to_any(1, 2, 3) # 1
621
default_to_any(None, 2, 3) # 2
622
```
623
624
### to_path
625
626
```python { .api }
627
def to_path(value: Any) -> List[Any]
628
```
629
630
Converts `value` to a property path array.
631
632
**Parameters:**
633
- `value` (`Any`): Value to convert.
634
635
**Returns:**
636
- `List[Any]`: Property path array.
637
638
**Example:**
639
```python { .api }
640
from pydash import to_path
641
642
to_path('a.b.c') # ['a', 'b', 'c']
643
to_path('a[0].b.c') # ['a', 0, 'b', 'c']
644
to_path(['a', 'b', 'c']) # ['a', 'b', 'c']
645
```
646
647
## Conditional and Control Flow
648
649
### cond
650
651
```python { .api }
652
def cond(pairs: List[Tuple[Callable, Callable]]) -> Callable
653
```
654
655
Creates a function that iterates over `pairs` and invokes the corresponding function of the first predicate to return truthy.
656
657
**Parameters:**
658
- `pairs` (`List[Tuple[Callable, Callable]]`): Predicate-function pairs.
659
660
**Returns:**
661
- `Callable`: New composite function.
662
663
**Example:**
664
```python { .api }
665
from pydash import cond
666
667
func = cond([
668
[lambda x: x == 0, lambda x: 'zero'],
669
[lambda x: x % 2 == 1, lambda x: 'odd'],
670
[lambda x: x % 2 == 0, lambda x: 'even']
671
])
672
673
func(0) # 'zero'
674
func(1) # 'odd'
675
func(2) # 'even'
676
```
677
678
### conforms
679
680
```python { .api }
681
def conforms(source: Dict[str, Callable]) -> Callable
682
```
683
684
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`.
685
686
**Parameters:**
687
- `source` (`Dict[str, Callable]`): Object of predicate properties.
688
689
**Returns:**
690
- `Callable`: New predicate function.
691
692
**Example:**
693
```python { .api }
694
from pydash import conforms, filter_
695
696
validator = conforms({
697
'age': lambda x: x >= 18,
698
'name': lambda x: len(x) >= 2
699
})
700
701
users = [
702
{'name': 'John', 'age': 25},
703
{'name': 'J', 'age': 17},
704
{'name': 'Jane', 'age': 30}
705
]
706
707
valid_users = filter_(users, validator) # [{'name': 'John', 'age': 25}, {'name': 'Jane', 'age': 30}]
708
```
709
710
### conforms_to
711
712
```python { .api }
713
def conforms_to(obj: Any, source: Dict[str, Callable]) -> bool
714
```
715
716
Checks if `obj` conforms to `source` by invoking the predicate properties of `source` with the corresponding property values of `obj`.
717
718
**Parameters:**
719
- `obj` (`Any`): Object to check.
720
- `source` (`Dict[str, Callable]`): Object of predicate properties.
721
722
**Returns:**
723
- `bool`: `True` if `obj` conforms, else `False`.
724
725
**Example:**
726
```python { .api }
727
from pydash import conforms_to
728
729
user = {'name': 'John', 'age': 25}
730
rules = {'age': lambda x: x >= 18, 'name': lambda x: len(x) >= 2}
731
732
conforms_to(user, rules) # True
733
```
734
735
### over_every
736
737
```python { .api }
738
def over_every(*predicates: Callable) -> Callable
739
```
740
741
Creates a function that checks if all of the `predicates` return truthy when invoked with the arguments it receives.
742
743
**Parameters:**
744
- `predicates` (`*Callable`): Predicates to check.
745
746
**Returns:**
747
- `Callable`: New predicate function.
748
749
**Example:**
750
```python { .api }
751
from pydash import over_every
752
753
is_positive_even = over_every(lambda x: x > 0, lambda x: x % 2 == 0)
754
is_positive_even(4) # True
755
is_positive_even(-2) # False
756
is_positive_even(3) # False
757
```
758
759
### over_some
760
761
```python { .api }
762
def over_some(*predicates: Callable) -> Callable
763
```
764
765
Creates a function that checks if any of the `predicates` return truthy when invoked with the arguments it receives.
766
767
**Parameters:**
768
- `predicates` (`*Callable`): Predicates to check.
769
770
**Returns:**
771
- `Callable`: New predicate function.
772
773
**Example:**
774
```python { .api }
775
from pydash import over_some
776
777
is_string_or_number = over_some(
778
lambda x: isinstance(x, str),
779
lambda x: isinstance(x, (int, float))
780
)
781
782
is_string_or_number('hello') # True
783
is_string_or_number(42) # True
784
is_string_or_number([]) # False
785
```
786
787
### over
788
789
```python { .api }
790
def over(*iteratees: Callable) -> Callable
791
```
792
793
Creates a function that invokes `iteratees` with the arguments it receives and returns their results.
794
795
**Parameters:**
796
- `iteratees` (`*Callable`): Iteratees to invoke.
797
798
**Returns:**
799
- `Callable`: New function.
800
801
**Example:**
802
```python { .api }
803
from pydash import over
804
805
func = over(max, min, len)
806
func([1, 2, 3, 4, 5]) # [5, 1, 5]
807
```
808
809
## Function Enhancement Utilities
810
811
### memoize
812
813
```python { .api }
814
def memoize(func: Callable, resolver: Callable = None) -> Callable
815
```
816
817
Creates a memoized version of `func` which caches the result of function calls.
818
819
**Parameters:**
820
- `func` (`Callable`): Function to memoize.
821
- `resolver` (`Callable`, optional): Function to resolve the cache key.
822
823
**Returns:**
824
- `Callable`: Memoized function.
825
826
**Example:**
827
```python { .api }
828
from pydash import memoize
829
830
@memoize
831
def expensive_function(n):
832
print(f"Computing for {n}")
833
return n * n
834
835
expensive_function(5) # "Computing for 5", returns 25
836
expensive_function(5) # Returns 25 (cached, no print)
837
```
838
839
### nth_arg
840
841
```python { .api }
842
def nth_arg(n: int = 0) -> Callable
843
```
844
845
Creates a function that gets the argument at index `n`. If `n` is negative, the nth argument from the end is returned.
846
847
**Parameters:**
848
- `n` (`int`): Index of argument to return. Defaults to `0`.
849
850
**Returns:**
851
- `Callable`: New function.
852
853
**Example:**
854
```python { .api }
855
from pydash import nth_arg
856
857
first_arg = nth_arg(0)
858
second_arg = nth_arg(1)
859
last_arg = nth_arg(-1)
860
861
first_arg('a', 'b', 'c') # 'a'
862
second_arg('a', 'b', 'c') # 'b'
863
last_arg('a', 'b', 'c') # 'c'
864
```
865
866
### result
867
868
```python { .api }
869
def result(obj: Any, path: Union[str, List], default: Any = None) -> Any
870
```
871
872
Resolves the value of property `path` on `object`. If the resolved value is a function, it's invoked with the `this` binding of its parent object and its result is returned.
873
874
**Parameters:**
875
- `obj` (`Any`): Object to query.
876
- `path` (`Union[str, List]`): Path of the property to resolve.
877
- `default` (`Any`): Value returned if the resolved value is `None`.
878
879
**Returns:**
880
- `Any`: Resolved value.
881
882
**Example:**
883
```python { .api }
884
from pydash import result
885
886
obj = {'a': {'b': lambda: 'hello'}}
887
result(obj, 'a.b') # 'hello' (function is called)
888
889
obj2 = {'a': {'b': 'world'}}
890
result(obj2, 'a.b') # 'world' (value is returned)
891
```
892
893
### retry
894
895
```python { .api }
896
def retry(func: Callable, times: int = 1, delay: int = 0, **kwargs: Any) -> Any
897
```
898
899
Retry function execution with specified number of attempts.
900
901
**Parameters:**
902
- `func` (`Callable`): Function to retry.
903
- `times` (`int`): Number of retry attempts. Defaults to `1`.
904
- `delay` (`int`): Delay between retries in milliseconds. Defaults to `0`.
905
- `kwargs` (`**Any`): Additional keyword arguments.
906
907
**Returns:**
908
- `Any`: Function result or raises last exception.
909
910
**Example:**
911
```python { .api }
912
from pydash import retry
913
import random
914
915
def flaky_function():
916
if random.random() < 0.7:
917
raise Exception("Random failure")
918
return "Success!"
919
920
# Retry up to 3 times with 100ms delay
921
result = retry(flaky_function, times=3, delay=100)
922
```
923
924
### properties
925
926
```python { .api }
927
def properties(obj: Any) -> List[str]
928
```
929
930
Creates a list of the own and inherited enumerable property names of `object`.
931
932
**Parameters:**
933
- `obj` (`Any`): Object to inspect.
934
935
**Returns:**
936
- `List[str]`: List of property names.
937
938
**Example:**
939
```python { .api }
940
from pydash import properties
941
942
class MyClass:
943
def __init__(self):
944
self.prop1 = 'value1'
945
self.prop2 = 'value2'
946
947
obj = MyClass()
948
properties(obj) # ['prop1', 'prop2'] (plus inherited properties)
949
```
950
951
## Usage Examples
952
953
### Configuration and Defaults
954
```python { .api }
955
from pydash import default_to, default_to_any, constant
956
957
def create_config(user_config=None):
958
config = {
959
'timeout': default_to(user_config.get('timeout') if user_config else None, 5000),
960
'retries': default_to(user_config.get('retries') if user_config else None, 3),
961
'debug': default_to(user_config.get('debug') if user_config else None, False)
962
}
963
return config
964
965
# Using constants for default callbacks
966
DEFAULT_SUCCESS = constant('Operation completed')
967
DEFAULT_ERROR = constant('Operation failed')
968
969
def api_call(endpoint, success_callback=DEFAULT_SUCCESS, error_callback=DEFAULT_ERROR):
970
# ... API logic
971
pass
972
```
973
974
### Property Access and Manipulation
975
```python { .api }
976
from pydash import property_, property_of, matches_property, map_
977
978
# Extract specific fields from data
979
users = [
980
{'id': 1, 'name': 'John', 'profile': {'email': 'john@example.com'}},
981
{'id': 2, 'name': 'Jane', 'profile': {'email': 'jane@example.com'}}
982
]
983
984
# Create property accessors
985
get_name = property_('name')
986
get_email = property_('profile.email')
987
988
names = map_(users, get_name) # ['John', 'Jane']
989
emails = map_(users, get_email) # ['john@example.com', 'jane@example.com']
990
991
# Filter by property value
992
is_john = matches_property('name', 'John')
993
john_user = filter_(users, is_john)
994
```
995
996
### Conditional Logic and Validation
997
```python { .api }
998
from pydash import cond, conforms, over_every, over_some
999
1000
# Complex conditional logic
1001
process_number = cond([
1002
[lambda x: x < 0, lambda x: f"Negative: {abs(x)}"],
1003
[lambda x: x == 0, constant("Zero")],
1004
[lambda x: x % 2 == 0, lambda x: f"Even: {x}"],
1005
[lambda x: True, lambda x: f"Odd: {x}"] # Default case
1006
])
1007
1008
# Data validation
1009
user_validator = conforms({
1010
'email': lambda x: '@' in x and '.' in x,
1011
'age': lambda x: isinstance(x, int) and 0 < x < 150,
1012
'name': lambda x: isinstance(x, str) and len(x.strip()) > 0
1013
})
1014
1015
# Complex predicates
1016
is_valid_number = over_every(
1017
lambda x: isinstance(x, (int, float)),
1018
lambda x: not math.isnan(x) if isinstance(x, float) else True,
1019
lambda x: x >= 0
1020
)
1021
```
1022
1023
### Memoization and Performance
1024
```python { .api }
1025
from pydash import memoize, times
1026
1027
# Expensive computation with caching
1028
@memoize
1029
def fibonacci(n):
1030
if n < 2:
1031
return n
1032
return fibonacci(n - 1) + fibonacci(n - 2)
1033
1034
# Custom cache key resolver
1035
@memoize(resolver=lambda args, kwargs: f"{args[0]}:{kwargs.get('precision', 2)}")
1036
def expensive_calculation(value, precision=2):
1037
# Simulate expensive operation
1038
return round(value ** 0.5, precision)
1039
1040
# Generate test data
1041
test_cases = times(10, lambda i: random.random() * 100)
1042
```
1043
1044
### Utility Factories and Helpers
1045
```python { .api }
1046
from pydash import method, method_of, nth_arg, unique_id
1047
1048
# Create method invokers
1049
uppercase = method('upper')
1050
split_lines = method('split', '\n')
1051
1052
# Process strings
1053
texts = ['hello world', 'foo\nbar\nbaz']
1054
upper_texts = map_(texts, uppercase) # ['HELLO WORLD', 'FOO\nBAR\nBAZ']
1055
1056
# Argument selectors for function composition
1057
get_first = nth_arg(0)
1058
get_second = nth_arg(1)
1059
get_last = nth_arg(-1)
1060
1061
# ID generation for resources
1062
generate_user_id = lambda: unique_id('user_')
1063
generate_session_id = lambda: unique_id('session_')
1064
1065
user_id = generate_user_id() # 'user_1'
1066
session_id = generate_session_id() # 'session_2'
1067
```
1068
1069
This Utilities module provides comprehensive helper functionality with 38 functions covering function creation, value generation, conditional logic, property access, and various utility patterns essential for functional programming and general application development.