-
Notifications
You must be signed in to change notification settings - Fork 87
/
objects.py
1328 lines (992 loc) · 34.9 KB
/
objects.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 -*-
"""Functions that operate on lists, dicts, and other objects.
.. versionadded:: 1.0.0
"""
from __future__ import absolute_import
import copy
import math
import re
import pydash as pyd
from .helpers import (
iterator,
itercallback,
get_item,
set_item,
NoValue,
callit,
getargcount
)
from ._compat import iteritems, text_type
__all__ = (
'assign',
'callables',
'clone',
'clone_deep',
'deep_get',
'deep_has',
'deep_set',
'deep_map_values',
'defaults',
'defaults_deep',
'extend',
'find_key',
'find_last_key',
'for_in',
'for_in_right',
'for_own',
'for_own_right',
'get',
'get_path',
'has',
'has_path',
'invert',
'keys',
'keys_in',
'map_keys',
'map_values',
'merge',
'methods',
'omit',
'pairs',
'parse_int',
'pick',
'rename_keys',
'set_',
'set_path',
'to_boolean',
'to_dict',
'to_number',
'to_plain_object',
'to_string',
'transform',
'update_path',
'values',
'values_in',
)
def assign(obj, *sources, **kargs):
"""Assigns own enumerable properties of source object(s) to the destination
object. If `callback` is supplied, it is invoked with two arguments:
``(obj_value, source_value)``.
Args:
obj (dict): Destination object whose properties will be modified.
sources (dict): Source objects to assign to `obj`.
Keyword Args:
callback (mixed, optional): Callback applied per iteration.
Returns:
dict: Modified `obj`.
Warning:
`obj` is modified in place.
Example:
>>> obj = {}
>>> obj2 = assign(obj, {'a': 1}, {'b': 2}, {'c': 3})
>>> obj == {'a': 1, 'b': 2, 'c': 3}
True
>>> obj is obj2
True
See Also:
- :func:`assign` (main definition)
- :func:`extend` (alias)
.. versionadded:: 1.0.0
.. versionchanged:: 2.3.2
Apply :func:`clone_deep` to each `source` before assigning to `obj`.
.. versionchanged:: 3.0.0
Allow callbacks to accept partial arguments.
"""
sources = list(sources)
callback = kargs.get('callback')
if callback is None and callable(sources[-1]):
callback = sources.pop()
argcount = (getargcount(callback, maxargs=2) if callback is not None
else None)
for source in sources:
source = clone_deep(source)
for key, value in iteritems(source):
obj[key] = (value if callback is None
else callit(callback,
obj.get(key),
value,
argcount=argcount))
return obj
extend = assign
def callables(obj):
"""Creates a sorted list of keys of an object that are callable.
Args:
obj (list|dict): Object to inspect.
Returns:
list: All keys whose values are callable.
Example:
>>> callables({'a': 1, 'b': lambda: 2, 'c': lambda: 3})
['b', 'c']
See Also:
- :func:`callables` (main definition)
- :func:`methods` (alias)
.. versionadded:: 1.0.0
.. versionchanged:: 2.0.0
Renamed ``functions`` to ``callables``.
"""
return sorted(key for key, value in iterator(obj) if callable(value))
methods = callables
def clone(value, is_deep=False, callback=None):
"""Creates a clone of `value`. If `is_deep` is ``True`` nested valueects
will also be cloned, otherwise they will be assigned by reference. If a
callback is provided it will be executed to produce the cloned values. The
callback is invoked with one argument: ``(value)``.
Args:
value (list|dict): Object to clone.
is_deep (bool, optional): Whether to perform deep clone.
callback (mixed, optional): Callback applied per iteration.
Example:
>>> x = {'a': 1, 'b': 2, 'c': {'d': 3}}
>>> y = clone(x)
>>> y == y
True
>>> x is y
False
>>> x['c'] is y['c']
True
>>> z = clone(x, is_deep=True)
>>> x == z
True
>>> x['c'] is z['c']
False
Returns:
list|dict: Cloned object.
.. versionadded:: 1.0.0
"""
if callback is None:
callback = pyd.identity
copier = copy.deepcopy if is_deep else copy.copy
value = copier(value)
obj = [(key, callback(val)) for key, val in iterator(value)]
if isinstance(value, list):
obj = [val for _, val in obj]
else:
obj = dict(obj)
return obj
def clone_deep(value, callback=None):
"""Creates a deep clone of `value`. If a callback is provided it will be
executed to produce the cloned values. The callback is invoked with one
argument: ``(value)``.
Args:
value (list|dict): Object to clone.
callback (mixed, optional): Callback applied per iteration.
Returns:
list|dict: Cloned object.
Example:
>>> x = {'a': 1, 'b': 2, 'c': {'d': 3}}
>>> y = clone_deep(x)
>>> y == y
True
>>> x is y
False
>>> x['c'] is y['c']
False
.. versionadded:: 1.0.0
"""
return clone(value, is_deep=True, callback=callback)
def deep_map_values(obj, callback=None, property_path=NoValue):
"""Map all non-object values in `obj` with return values from `callback`.
The callback is invoked with two arguments: ``(obj_value, property_path)``
where ``property_path`` contains the list of path keys corresponding to the
path of ``obj_value``.
Args:
obj (list|dict): Object to map.
callback (function): Callback applied to each value.
Returns:
mixed: The modified object.
Warning:
`obj` is modified in place.
Example:
>>> x = {'a': 1, 'b': {'c': 2}}
>>> y = deep_map_values(x, lambda val: val * 2)
>>> y == {'a': 2, 'b': {'c': 4}}
True
>>> z = deep_map_values(x, lambda val, props: props)
>>> z == {'a': ['a'], 'b': {'c': ['b', 'c']}}
True
.. versionadded: 2.2.0
.. versionchanged:: 3.0.0
Allow callbacks to accept partial arguments.
"""
properties = path_keys(property_path)
if pyd.is_object(obj):
deep_callback = (
lambda value, key: deep_map_values(value,
callback,
pyd.flatten([properties, key])))
return pyd.extend(obj, map_values(obj, deep_callback))
else:
return callit(callback, obj, properties)
def defaults(obj, *sources):
"""Assigns own enumerable properties of source object(s) to the destination
object for all destination properties that resolve to undefined.
Args:
obj (dict): Destination object whose properties will be modified.
sources (dict): Source objects to assign to `obj`.
Returns:
dict: Modified `obj`.
Warning:
`obj` is modified in place.
Example:
>>> obj = {'a': 1}
>>> obj2 = defaults(obj, {'b': 2}, {'c': 3}, {'a': 4})
>>> obj is obj2
True
>>> obj == {'a': 1, 'b': 2, 'c': 3}
True
.. versionadded:: 1.0.0
"""
for source in sources:
for key, value in iteritems(source):
obj.setdefault(key, value)
return obj
def defaults_deep(obj, *sources):
"""This method is like :func:`defaults` except that it recursively assigns
default properties.
Args:
obj (dict): Destination object whose properties will be modified.
sources (dict): Source objects to assign to `obj`.
Returns:
dict: Modified `obj`.
Warning:
`obj` is modified in place.
Example:
>>> obj = {'a': {'b': 1}}
>>> obj2 = defaults_deep(obj, {'a': {'b': 2, 'c': 3}})
>>> obj is obj2
True
>>> obj == {'a': {'b': 1, 'c': 3}}
True
.. versionadded:: 3.3.0
"""
def setter(obj, key, value):
obj.setdefault(key, value)
return merge(obj, *sources, _setter=setter)
def find_key(obj, callback=None):
"""This method is like :func:`pydash.arrays.find_index` except that it
returns the key of the first element that passes the callback check,
instead of the element itself.
Args:
obj (list|dict): Object to search.
callback (mixed): Callback applied per iteration.
Returns:
mixed: Found key or ``None``.
Example:
>>> find_key({'a': 1, 'b': 2, 'c': 3}, lambda x: x == 1)
'a'
>>> find_key([1, 2, 3, 4], lambda x: x == 1)
0
See Also:
- :func:`find_key` (main definition)
- :func:`find_last_key` (alias)
.. versionadded:: 1.0.0
"""
for result, _, key, _ in itercallback(obj, callback):
if result:
return key
find_last_key = find_key
def for_in(obj, callback=None):
"""Iterates over own and inherited enumerable properties of `obj`,
executing `callback` for each property.
Args:
obj (list|dict): Object to process.
callback (mixed): Callback applied per iteration.
Returns:
list|dict: `obj`.
Example:
>>> obj = {}
>>> def cb(v, k): obj[k] = v
>>> results = for_in({'a': 1, 'b': 2, 'c': 3}, cb)
>>> results == {'a': 1, 'b': 2, 'c': 3}
True
>>> obj == {'a': 1, 'b': 2, 'c': 3}
True
See Also:
- :func:`for_in` (main definition)
- :func:`for_own` (alias)
.. versionadded:: 1.0.0
"""
walk = (None for ret, _, _, _ in itercallback(obj, callback)
if ret is False)
next(walk, None)
return obj
for_own = for_in
def for_in_right(obj, callback=None):
"""This function is like :func:`for_in` except it iterates over the
properties in reverse order.
Args:
obj (list|dict): Object to process.
callback (mixed): Callback applied per iteration.
Returns:
list|dict: `obj`.
Example:
>>> data = {'product': 1}
>>> def cb(v): data['product'] *= v
>>> for_in_right([1, 2, 3, 4], cb)
[1, 2, 3, 4]
>>> data['product'] == 24
True
See Also:
- :func:`for_in_right` (main definition)
- :func:`for_own_right` (alias)
.. versionadded:: 1.0.0
"""
walk = (None for ret, _, _, _ in itercallback(obj, callback, reverse=True)
if ret is False)
next(walk, None)
return obj
for_own_right = for_in_right
def get(obj, path, default=None):
"""Get the value at any depth of a nested object based on the path
described by `path`. If path doesn't exist, `default` is returned.
Args:
obj (list|dict): Object to process.
path (str|list): List or ``.`` delimited string of path describing
path.
Keyword Arguments:
default (mixed): Default value to return if path doesn't exist.
Defaults to ``None``.
Returns:
mixed: Value of `obj` at path.
Example:
>>> get({}, 'a.b.c') is None
True
>>> get({'a': {'b': {'c': [1, 2, 3, 4]}}}, 'a.b.c.1')
2
>>> get({'a': {'b': [0, {'c': [1, 2]}]}}, 'a.b.1.c.1')
2
>>> get({'a': {'b': [0, {'c': [1, 2]}]}}, 'a.b.1.c.2') is None
True
See Also:
- :func:`get` (main definition)
- :func:`get_path` (alias)
- :func:`deep_get` (alias)
.. versionadded:: 2.0.0
.. versionchanged:: 2.2.0
Support escaping "." delimiter in single string path key.
.. versionchanged:: 3.3.0
- Added :func:`get` as main definition and :func:`get_path` as alias.
- Made :func:`deep_get` an alias.
"""
for key in path_keys(path):
obj = get_item(obj, key, default=default)
if obj is None:
break
return obj
get_path = get
deep_get = get
def has(obj, path):
"""Checks if `path` exists as a key of `obj`.
Args:
obj (mixed): Object to test.
path (mixed): Path to test for. Can be a list of nested keys or a ``.``
delimited string of path describing the path.
Returns:
bool: Whether `obj` has `path`.
Example:
>>> has([1, 2, 3], 1)
True
>>> has({'a': 1, 'b': 2}, 'b')
True
>>> has({'a': 1, 'b': 2}, 'c')
False
>>> has({'a': {'b': [0, {'c': [1, 2]}]}}, 'a.b.1.c.1')
True
>>> has({'a': {'b': [0, {'c': [1, 2]}]}}, 'a.b.1.c.2')
False
See Also:
- :func:`has` (main definition)
- :func:`deep_has` (alias)
- :func:`has_path` (alias)
.. versionadded:: 1.0.0
.. versionchanged:: 3.0.0
Return ``False`` on ``ValueError`` when checking path.
.. verisionchanged:: 3.3.0
- Added :func:`deep_has` as alias.
- Added :func:`has_path` as alias.
"""
try:
get(obj, path, default=NoValue)
exists = True
except (KeyError, IndexError, TypeError, ValueError):
exists = False
return exists
deep_has = has
has_path = has
def invert(obj, multivalue=False):
"""Creates an object composed of the inverted keys and values of the given
object.
Args:
obj (dict): Dict to invert.
multivalue (bool, optional): Whether to return inverted values as
lists. Defaults to ``False``.
Returns:
dict: Inverted dict.
Example:
>>> results = invert({'a': 1, 'b': 2, 'c': 3})
>>> results == {1: 'a', 2: 'b', 3: 'c'}
True
>>> results = invert({'a': 1, 'b': 2, 'c': 1}, multivalue=True)
>>> set(results[1]) == set(['a', 'c'])
True
Note:
Assumes `dict` values are hashable as `dict` keys.
.. versionadded:: 1.0.0
.. versionchanged:: 2.0.0
Added ``multivalue`` argument.
"""
result = {}
for key, value in iterator(obj):
if multivalue:
result.setdefault(value, []).append(key)
else:
result[value] = key
return result
def keys(obj):
"""Creates a list composed of the keys of `obj`.
Args:
obj (mixed): Object to extract keys from.
Returns:
list: List of keys.
Example:
>>> keys([1, 2, 3])
[0, 1, 2]
>>> set(keys({'a': 1, 'b': 2, 'c': 3})) == set(['a', 'b', 'c'])
True
See Also:
- :func:`keys` (main definition)
- :func:`keys_in` (alias)
.. versionadded:: 1.0.0
.. versionchanged:: 1.1.0
Added :func:`keys_in` as alias.
"""
return [key for key, _ in iterator(obj)]
keys_in = keys
def map_keys(obj, callback=None):
"""Creates an object with the same values as `obj` and keys generated by
running each property of `obj` through the `callback`. The callback is
invoked with three arguments: ``(value, key, object)``. If a property name
is provided for `callback` the created :func:`pydash.collections.pluck`
style callback will return the property value of the given element. If an
object is provided for callback the created
:func:`pydash.collections.where` style callback will return ``True``
for elements that have the properties of the given object, else ``False``.
Args:
obj (list|dict): Object to map.
callback (mixed): Callback applied per iteration.
Returns:
list|dict: Results of running `obj` through `callback`.
Example:
>>> callback = lambda value, key: key * 2
>>> results = map_keys({'a': 1, 'b': 2, 'c': 3}, callback)
>>> results == {'aa': 1, 'bb': 2, 'cc': 3}
True
.. versionadded:: 3.3.0
"""
return dict((result, value)
for result, value, _, _ in itercallback(obj, callback))
def map_values(obj, callback=None):
"""Creates an object with the same keys as `obj` and values generated by
running each property of `obj` through the `callback`. The callback is
invoked with three arguments: ``(value, key, object)``. If a property name
is provided for `callback` the created :func:`pydash.collections.pluck`
style callback will return the property value of the given element. If an
object is provided for callback the created
:func:`pydash.collections.where` style callback will return ``True``
for elements that have the properties of the given object, else ``False``.
Args:
obj (list|dict): Object to map.
callback (mixed): Callback applied per iteration.
Returns:
list|dict: Results of running `obj` through `callback`.
Example:
>>> results = map_values({'a': 1, 'b': 2, 'c': 3}, lambda x: x * 2)
>>> results == {'a': 2, 'b': 4, 'c': 6}
True
>>> results = map_values({'a': 1, 'b': {'d': 4}, 'c': 3}, {'d': 4})
>>> results == {'a': False, 'b': True, 'c': False}
True
.. versionadded:: 1.0.0
"""
return dict((key, result)
for result, _, key, _ in itercallback(obj, callback))
def merge(obj, *sources, **kargs):
"""Recursively merges own enumerable properties of the source object(s)
that don't resolve to undefined into the destination object. Subsequent
sources will overwrite property assignments of previous sources. If a
callback is provided it will be executed to produce the merged values of
the destination and source properties. If the callback returns undefined
merging will be handled by the method instead. The callback is invoked with
at least two arguments: ``(obj_value, *source_value)``.
Args:
obj (dict): Destination object to merge source(s) into.
sources (dict): Source objects to merge from. subsequent sources
overwrite previous ones.
Keyword Args:
callback (function, optional): Callback function to handle merging
(must be passed in as keyword argument).
Returns:
dict: Merged object.
Warning:
`obj` is modified in place.
Example:
>>> obj = {'a': 2}
>>> obj2 = merge(obj, {'a': 1}, {'b': 2, 'c': 3}, {'d': 4})
>>> obj2 == {'a': 1, 'b': 2, 'c': 3, 'd': 4}
True
>>> obj is obj2
True
.. versionadded:: 1.0.0
.. versionchanged:: 2.3.2
Apply :func:`clone_deep` to each `source` before assigning to `obj`.
.. versionchanged:: 2.3.2
Allow `callback` to be passed by reference if it is the last positional
argument.
.. versionchanged:: 3.3.0
Added internal option for overriding the default setter for obj values.
"""
sources = list(sources)
_clone = kargs.get('_clone', True)
callback = kargs.get('callback')
setter = kargs.get('_setter', set_item)
if callback is None and callable(sources[-1]):
callback = sources.pop()
for source in sources:
# Don't re-clone if we've already cloned before.
if _clone:
source = clone_deep(source)
for key, src_value in iterator(source):
obj_value = get_item(obj, key, default=None)
all_sequences = all([isinstance(src_value, list),
isinstance(obj_value, list)])
all_mappings = all([isinstance(src_value, dict),
isinstance(obj_value, dict)])
if callback:
result = callback(obj_value, src_value)
elif all_sequences or all_mappings:
result = merge(obj_value,
src_value,
_clone=False,
_setter=setter)
else:
result = src_value
setter(obj, key, result)
return obj
def omit(obj, callback=None, *properties):
"""Creates a shallow clone of object excluding the specified properties.
Property names may be specified as individual arguments or as lists of
property names. If a callback is provided it will be executed for each
property of object omitting the properties the callback returns truthy for.
The callback is invoked with three arguments: ``(value, key, object)``.
Args:
obj (mixed): Object to process.
properties (str): Property values to omit.
callback (mixed, optional): Callback used to determine whic properties
to omit.
Returns:
dict: Results of omitting properties.
Example:
>>> omit({'a': 1, 'b': 2, 'c': 3}, 'b', 'c') == {'a': 1}
True
>>> omit([1, 2, 3, 4], 0, 3) == {1: 2, 2: 3}
True
.. versionadded:: 1.0.0
"""
if not callable(callback):
callback = callback if callback is not None else []
properties = pyd.flatten_deep([callback, properties])
# pylint: disable=missing-docstring,function-redefined
def callback(value, key, item):
return key in properties
argcount = 3
else:
argcount = getargcount(callback, maxargs=3)
return dict((key, value) for key, value in iterator(obj)
if not callit(callback, value, key, obj, argcount=argcount))
def pairs(obj):
"""Creates a two dimensional list of an object's key-value pairs, i.e.
``[[key1, value1], [key2, value2]]``.
Args:
obj (mixed): Object to process.
Returns:
list: Two dimensional list of object's key-value pairs.
Example:
>>> pairs([1, 2, 3, 4])
[[0, 1], [1, 2], [2, 3], [3, 4]]
>>> pairs({'a': 1})
[['a', 1]]
.. versionadded:: 1.0.0
"""
return [[key, value] for key, value in iterator(obj)]
def parse_int(value, radix=None):
"""Converts the given `value` into an integer of the specified `radix`. If
`radix` is falsey, a radix of ``10`` is used unless the `value` is a
hexadecimal, in which case a radix of 16 is used.
Args:
value (mixed): Value to parse.
radix (int, optional): Base to convert to.
Returns:
mixed: Integer if parsable else ``None``.
Example:
>>> parse_int('5')
5
>>> parse_int('12', 8)
10
>>> parse_int('x') is None
True
.. versionadded:: 1.0.0
"""
if not radix and pyd.is_string(value):
try:
# Check if value is hexadcimal and if so use base-16 conversion.
int(value, 16)
except ValueError:
pass
else:
radix = 16
if not radix:
radix = 10
try:
# NOTE: Must convert value to string when supplying radix to int().
# Dropping radix arg when 10 is needed to allow floats to parse
# correctly.
args = (value,) if radix == 10 else (to_string(value), radix)
parsed = int(*args)
except (ValueError, TypeError):
parsed = None
return parsed
def pick(obj, callback=None, *properties):
"""Creates a shallow clone of object composed of the specified properties.
Property names may be specified as individual arguments or as lists of
property names. If a callback is provided it will be executed for each
property of object picking the properties the callback returns truthy for.
The callback is invoked with three arguments: ``(value, key, object)``.
Args:
obj (list|dict): Object to pick from.
properties (str): Property values to pick.
callback (mixed, optional): Callback used to determine which properties
to pick.
Returns:
dict: Dict containg picked properties.
Example:
>>> pick({'a': 1, 'b': 2, 'c': 3}, 'a', 'b') == {'a': 1, 'b': 2}
True
.. versionadded:: 1.0.0
"""
if not callable(callback):
callback = callback if callback is not None else []
properties = pyd.flatten_deep([callback, properties])
# pylint: disable=missing-docstring,function-redefined
def callback(value, key, item):
return key in properties
argcount = 3
else:
argcount = getargcount(callback, maxargs=3)
# TODO: cache argcount
return dict((key, value) for key, value in iterator(obj)
if callit(callback, value, key, obj, argcount=argcount))
def rename_keys(obj, key_map):
"""Rename the keys of `obj` using `key_map` and return new object.
Args:
obj (dict): Object to rename.
key_map (dict): Renaming map whose keys correspond to existing keys in
`obj` and whose values are the new key name.
Returns:
dict: Renamed `obj`.
Example:
>>> obj = rename_keys({'a': 1, 'b': 2, 'c': 3}, {'a': 'A', 'b': 'B'})
>>> obj == {'A': 1, 'B': 2, 'c': 3}
True
.. versionadded:: 2.0.0
"""
return dict((key_map.get(key, key), value)
for key, value in iteritems(obj))
def set_(obj, path, value):
"""Sets the value of an object described by `path`. If any part of the
object path doesn't exist, it will be created.
Args:
obj (list|dict): Object to modify.
path (str | list): Target path to set value to.
value (mixed): Value to set.
Returns:
mixed: Modified `obj`.
Example:
>>> set_({}, 'a.b.c', 1)
{'a': {'b': {'c': 1}}}
>>> set_({}, 'a.0.c', 1)
{'a': {'0': {'c': 1}}}
>>> set_([1, 2], '2.0', 1)
[1, 2, [1]]
.. versionadded:: 2.2.0
.. versionchanged:: 3.3.0
Added :func:`set_` as main definition and :func:`deep_set` as alias.
"""
return set_path(obj, value, path_keys(path))
deep_set = set_
def set_path(obj, value, keys, default=None):
"""Sets the value of an object described by `keys`. If any part of the
object path doesn't exist, it will be created with `default`.
Args:
obj (list|dict): Object to modify.
value (mixed): Value to set.
keys (list): Target path to set value to.
default (callable, optional): Callable that returns default value to
assign if path part is not set. Defaults to ``{}`` if `obj` is a
``dict`` or ``[]`` if `obj` is a ``list``.
Returns:
mixed: Modified `obj`.
Example:
>>> set_path({}, 1, ['a', 0], default=[])
{'a': [1]}
>>> set_path({}, 1, ['a', 'b']) == {'a': {'b': 1}}
True
.. versionadded:: 2.0.0
"""
# pylint: disable=redefined-outer-name