-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpydict.py
1255 lines (1042 loc) · 41.2 KB
/
pydict.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
import _collections_abc
import sys as _sys
import types as _types
#####################################################
### Internal classes, constants, and variables.
####################################################
# Minimum pydict size
_MIN_SIZE = 8
#Resize function
def _resize_pydict(pd, size):
# Self is the pd
self = pd
# Get a copy of the items - now!
items = tuple(self.items())
# Double size
self._size = size
# Reset hash tables
self._hash_table = [None] * self._size
# Set all keys to their values
for k, v in items:
self[k] = v
#Ids of pydicts (or frozenpydicts) being repr'ed
_repr_pydicts = set()
class _Node(object):
__slots__ = "hashcode", "key", "value", "overflow"
def __init__(self, hashcode, key, value, overflow=None):
self.hashcode = hashcode
self.key = key
self.value = value
self.overflow = overflow
def __eq__(self, other):
if not isinstance(other, _Node):
return NotImplemented
return (self.hashcode, self.key, self.value, self.overflow) == \
(other.hashcode, other.key, other.value, other.overflow)
def __repr__(self):
return "pydict._Node(hashcode={}, key={}, value={}, overflow={})".format(
self.hashcode, repr(self.key), repr(self.value), self.overflow
)
def __sizeof__(self):
# Note: Omit key and value because they aren't internal
# Get size of self and size of self's hashcode
size = object.__sizeof__(self) + int.__sizeof__(self.hashcode)
# Get the size of all overflow nodes
node = self
while node.overflow != None:
node = node.overflow
size += object.__sizeof__(node) + int.__sizeof__(node.hashcode)
# We are done! Return the total
return size
def copy(self):
result = _Node(self.hashcode, self.key, self.value, self.overflow)
n = result
while isinstance(n.overflow, _Node):
o = n.overflow
n.overflow = _Node(o.hashcode, o.key, o.value, o.overflow)
n = n.overflow
return result
_marker = object()
####################################################
### pydict
####################################################
class pydict(object):
"""Python implementation of builtins.dict
pydict() -> new empty python dictionary
pydict(mapping) -> new python dictionary initialized from the mapping's (key, value) pairs
pydict(iterable) -> new python dictionary initialized via:
p = pydict()
for key, value in iterable:
p[key] = value
pydict(**kwds) -> new python dictionary initialized from the keyword arguments (name, value) pairs
"""
__slots__ = (
"_keys", "_hash_table", "_size"
)
def __new__(cls, mapping_or_iterable=(), /, **kwds):
# Get a raw object from object.__new__
self = object.__new__(cls)
# Initiate private fields
self._keys = []
self._size = _MIN_SIZE
self._hash_table = [None] * self._size
# Update self using mapping_or_iterable and kwds
self.update(mapping_or_iterable, **kwds)
# Return the modified object
return self
__class_getitem__ = classmethod(_types.GenericAlias)
def __contains__(self, key):
"Return key in self."
# Is this object in my keys?
return key in self.keys()
def __copy__(self):
"Implement copy.copy(self)."
return self.copy()
def __delitem__(self, key):
"Delete self[key]."
# Ge the hash code of the key. Trim it to size.
h = hash(key) % self._size
# The previous node
prev = None
# The current node
node = self._hash_table[h]
# While the current node isn't None...
while node is not None:
# Is this the corresponding node?
if node.hashcode == h and node.key == key:
# If so, is there a previous node in the overflow chain?
if prev is not None:
# If so, chain this node's overflow to the previous node's overflow
prev.overflow = node.overflow
else:
# Otherwise, the node's overflow is the new reference in the hash slot
self._hash_table[h] = node.overflow
# Remove the key from the pydict's keys
self._keys.remove(key)
# Avoid future iteration and the upcoming else statement
break
# Set the previous node to the current, the current to the current's overflow
prev = node
node = node.overflow
else:
# Raise KeyError
raise KeyError(key)
def __eq__(self, other):
"Return self==other"
# Are self and other the same class? If not, return NotImplemented
if not isinstance(other, _collections_abc.Mapping):
return NotImplemented
# Check false with unequal length
if len(self) != len(other):
return False
# Iterate over my keys
for key in self:
# If other[key] is absent or unequal to self[key]
# Return False
try:
if self[key] != other[key]:
return False
except KeyError:
return False
return True
def __getitem__(self, key):
"Return self[key]."
# Get the hash value of the key. Trim it to be within
# the size (# of buckets available)
h = hash(key) % self._size
# Get the result from the hash table.
result = self._hash_table[h]
# If there is no node, probe __missing__
if result is None:
return self.__missing__(key)
# Set node to the first node
node = result
# Check for the correct node. If so return its value.
if node.hashcode == h and node.key == key:
return node.value
# Search the overflow. Is the a correct node?
while node.overflow is not None:
node = node.overflow
# If so, return its value.
if node.hashcode == h and node.key == key:
return node.value
# There is no corresponding node. Probe missing.
return self.__missing__(key)
# No hash code, as we are mutable.
__hash__ = None
def __ior__(self, value):
"Return self|=value"
self.update(value)
return self
def __iter__(self):
"Return iter(self)"
# Return the iterator of a copy of this object's keys
return iter(self.keys())
def __len__(self):
"Return len(self)."
# Return the length of my keys.
return len(self._keys)
def __missing__(self, key):
"Fallback method when self[key] fails. \nRaises KeyError(key) by default."
raise KeyError(key)
def __ne__(self, other):
"Return self!=other"
# Return the opposite of self==other
if not isinstance(other, _collections_abc.Mapping):
return NotImplemented
return not (self == other)
def __or__(self, value):
"Return self|value"
pd = self.copy()
return pd.__ior__(value)
def __repr__(self):
"Return repr(self)"
# If within the midst of another repr call on the same object,
# return a filler value
if id(self) in _repr_pydicts:
return "pydict({...})"
# Add this object to the set of current repr calls
_repr_pydicts.add(id(self))
# A list of parts, to be joined
parts = []
# Every part is key: value
for key, value in self.items():
parts.append(": ".join([repr(key), repr(value)]))
# There is no opportunity left for recursion. Therefore, remove
# this object from the set of current repr calls
_repr_pydicts.remove(id(self))
# Join all the parts with ", " add preceeding and suceeding strings.
# Return the new string.
return "pydict({" + ", ".join(parts) + "})"
def __reversed__(self):
"Return reversed(self)."
return reversed(self.keys())
def __ror__(self, value):
"Return value|self"
return self.__or__(value)
def __setitem__(self, key, value):
"Set self[key] to value."
# Resize if necessary (new length will be > threshold)
threshold = 2 / 3
if (len(self) + 1) / (self._size) > threshold:
_resize_pydict(self, self._size * 2)
# Get the key's hash code. Trim it to be within the current size.
h = hash(key) % self._size
# Get the absolute value of the trimmed hash code
h = abs(h)
# Append to keys, if not already a key
if key not in self.keys():
self._keys.append(key)
# Get the node at the slot in the hash table
node = self._hash_table[h]
# If none, make a new corresponding node
if node is None:
self._hash_table[h] = _Node(hash(key) % self._size, key, value, None)
# Otherwise...
else:
while True:
# If there is a corresponding node, update its value
if node.hashcode == h and node.key == key:
node.value = value
break
# If there can't be a corresponding node, chain the
# corresponding to the last existing node.
if node.overflow is None:
node.overflow = _Node(hash(key) % self._size, key, value, None)
break
# Continue searching the overflow
node = node.overflow
def __sizeof__(self):
"Size of object in memory, in bytes."
# Get the raw size of the object
size = object.__sizeof__(self)
# Get size of internal keys list.
# Its keys aren't private, so don't calculate their sizes
size += self._keys.__sizeof__()
# Get size of the internal size counter.
# TODO: delete the internal size counter and use len(self._hash_table) instead
size += self._size.__sizeof__()
# Get the size of internal hash table
size += self._hash_table.__sizeof__()
# Get the size of the internal nodes
for obj in self._hash_table:
# Ignore None because None is public
if isinstance(obj, _Node):
# Get the size of all the nodes
size += obj.__sizeof__()
# That's the size!
return size
def clear(self):
"Remove all items from self."
# Iterate over every key, deleting it.
for key in self.keys():
del self[key]
def copy(self):
"Return a shallow copy of self."
return self.__class__(self)
@classmethod
def fromkeys(cls, keys, value=None):
"""
Create and return a new pydict, p, of type cls.
For every key in keys, p[key] = value.
"""
pd = cls()
pd.update(zip(keys, [value] * len(list(keys))))
return pd
def get(self, key, default=None):
"""Return self[key] if key in self, else default."""
try:
if isinstance(self, defaultpydict):
if key not in self.keys():
return default
return self[key]
except KeyError:
return default
def items(self):
"Return a view of self's items."
return PyDictItemView(self)
def keys(self):
"Return a view for self's keys."
# Return a copy of the internal keys list
return PyDictKeyView(self)
def move_to_end(self, key, last=True):
"""Move a key to the back of the pydict.
If last is False, move the key to the front of the pydict instead.
Raises KeyError if key not in the pydict.
"""
# Find the actual key (in case an equivalent was passed in)
keys = self.keys()
for i in range(len(keys)):
if key == keys[i]:
# Remove the key from my keys list, assign it to the key parameter
key = self._keys.pop(i)
break
else:
# Raise KeyError if there is no corresponding key
raise KeyError("Key not in pydict")
if last:
# Insert the removed key at the back of my keys list
self._keys.append(key)
else:
# Insert the removed key at the front of my keys list
self._keys.insert(0, key)
def pop(self, key, default=_marker):
"""Remove key from self, return self[key].
If key is not found, return default if given, otherwise raise KeyError."""
try:
# Get the value associated with the key
value = self[key]
# Delete the key...
del self[key]
except KeyError:
# If no default provided when the key isn't present, raise KeyError
# However, return the default if provided
if default is _marker:
raise
return default
else:
#...return its value
return value
def popitem(self, last=True):
"""Removes a key, return a 2-tuple: (the key, its associated value).
Removes last key if last is True, otherwise first key.
Raises KeyError if pydict is empty."""
# Check if I am empty
if len(self) == 0:
raise KeyError("pydict is empty.")
if last:
# The key is the last key
key = self.keys()[-1]
else:
# The key is the first key
key = self.keys()[0]
# Remove the key. Return (the key, its associated value).
return key, self.pop(key)
def setdefault(self, key, default=None):
"""Set self[key] to default if key not in pydict.
Return self[key]."""
# Set self[key] to default if key not in me
if key not in self:
self[key] = default
# Return self[key]
return self[key]
def update(self, mapping_or_iterable=(), /, **kwds):
"""p.update(Q, **R)
Update self from Q and R.
If Q is present and has a .keys() method, then does: for k in Q: self[k] = Q[k]
If Q is present and lacks a .keys() method, then does: for k, v in Q: self[k] = v
In either case, this is followed by: for k in R: self[k] = R[k]
"""
# Get the value associated with Q's keys attribute.
# If Q doesn't have a keys attribute, get None instead
keysfunc = getattr(mapping_or_iterable, "keys", None)
# If the value is callable, it is the keys() method.
# Call it to get an iterable of Q's keys. Then, for
# k in Q's keys, set self[k] to Q[k].
if callable(keysfunc):
for key in keysfunc():
self[key] = mapping_or_iterable[key]
# Otherwise, for k, v in Q, set self[k] to v.
else:
for key, value in mapping_or_iterable:
self[key] = value
# For k in kwds, set self[k] to kwds[k]
for key in kwds:
self[key] = kwds[key]
def values(self):
"Return a view of self's values."
# Iterate over the keys. Return the corresponding values.
return PyDictValueView(self)
_collections_abc.MutableMapping.register(pydict)
#####################################################
### frozenpydict
####################################################
class frozenpydict(object):
"""Immutable version of pydict
frozenpydict() -> new empty frozen python dictionary
frozenpydict(mapping) -> new frozen python dictionary initialized from the mapping's (key, value) pairs
frozenpydict(iterable) -> new frozen python dictionary initialized via:
frozendict(pydict(iterable))
frozenpydict(**kwds) -> new frozen python dictionary initialized from the keyword arguments (name, value) pairs
"""
__slots__ = "_keys", "_frozen_hash_table", "_size"
def __new__(cls, mapping_or_iterable=(), /, **kwds):
# Get a raw object
self = object.__new__(cls)
# Make a mutable pydict with arguments
pd = pydict(mapping_or_iterable, **kwds)
# Assign self's attributes, independent but resembling pd's attributes
self._keys, self._frozen_hash_table, self._size = \
tuple(pd._keys), tuple(pd._hash_table), pd._size
# No need to obsucre pd, as nobody else may access it.
# That's it! Return self.
return self
def __contains__(self, key):
"Return key in self."
# Is this object in my keys?
return key in self.keys()
__class_getitem__ = classmethod(_types.GenericAlias)
def __eq__(self, other):
"Return self==other"
# Are self and other the same class? If not, return NotImplemented
if not isinstance(other, _collections_abc.Mapping):
return NotImplemented
# Check false with unequal length
if len(self) != len(other):
return False
# Iterate over my keys
for key in self:
# If other[key] is absent or unequal to self[key]
# Return False
try:
if self[key] != other[key]:
return False
except KeyError:
return False
return True
def __getitem__(self, key):
"Return self[key]."
# Get the hash value of the key. Trim it to be within
# the size (# of buckets available)
h = hash(key) % self._size
# Get the result from the hash table.
result = self._frozen_hash_table[h]
# If there is no node, raise KeyError
if result is None:
raise KeyError(key)
# Set node to the first node
node = result
# Check for the correct node. If so return its value.
if node.hashcode == h and node.key == key:
return node.value
# Search the overflow. Is the a correct node?
while node.overflow is not None:
node = node.overflow
# If so, return its value.
if node.hashcode == h and node.key == key:
return node.value
# There is no corresponding node. Raise KeyError.
raise KeyError(key)
def __hash__(self):
h_items = hash(frozenset(self.items()))
h = ((h_items << 5) * 31 >> 6) // -7
if h == -1:
return 713144892
return h
# Avoid subclassing
__init_subclass__ = None
def __ior__(self, value):
"Return self |= value"
raise TypeError("'|=' not supported by frozenpydict. Use '|' instead.")
def __iter__(self):
"Return iter(self)"
# Return the iterator of a copy of this object's keys
return iter(self.keys())
def __len__(self):
"Return len(self)."
# Return the length of my keys.
return len(self._keys)
def __ne__(self, other):
"Return self!=other"
if not isinstance(other, _collections_abc.Mapping):
return NotImplemented
# Return the opposite of self==other
return not (self == other)
def __or__(self, value):
"Return self|value"
pd = pydict(self)
pd.update(value)
return frozenpydict(pd)
def __repr__(self):
"Return repr(self)"
# If within the midst of another repr call on the same object,
# return a filler value
if id(self) in _repr_pydicts:
return "frozenpydict({...})"
# Add this object to the set of current repr calls
_repr_pydicts.add(id(self))
# A list of parts, to be joined
parts = []
# Every part is key: value
for key, value in self.items():
parts.append(": ".join([repr(key), repr(value)]))
# There is no opportunity left for recursion. Therefore, remove
# this object from the set of current repr calls
_repr_pydicts.remove(id(self))
# Join all the parts with ", " add preceeding and suceeding strings.
# Return the new string.
return "frozenpydict({" + ", ".join(parts) + "})"
def __reversed__(self):
"Return reversed(self)"
# Return a reverse of my iterator
return reversed(self.keys())
def __ror__(self, value):
"Return value|self"
return self.__or__(value)
def __sizeof__(self):
# Get the size of the private internal slots
size = object.__sizeof__(self)
size += self._keys.__sizeof__()
size += self._size.__sizeof__()
size += self._frozen_hash_table.__sizeof__()
# Get the size of the internal nodes
for obj in self._frozen_hash_table:
if isinstance(obj, _Node):
size += obj.__sizeof__()
# That's the size!
return size
@classmethod
def fromkeys(cls, keys, value=None):
"""
Create and return a new frozenpydict, p.
For every key in keys, p[key] = value.
"""
return frozenpydict(zip(keys, [value] * len(list(keys))))
def get(self, key, default=None):
"Return self[key] if key in self, else default."
try:
return self[key]
except KeyError:
return default
def items(self):
"Return a view of self's items."
return PyDictItemView(self)
def keys(self):
"Return a view for self's keys."
return PyDictKeyView(self)
def values(self):
"Return a view for self's values."
return PyDictValueView(self)
_collections_abc.Mapping.register(frozenpydict)
#####################################################
### OrderedPyDict
####################################################
class OrderedPyDict(pydict):
"""Python dictionary that remembers insertion order.
See help(pydict) for signature of constructor.
"""
def __eq__(self, other):
"Return self==other"
if not isinstance(other, OrderedPyDict):
return NotImplemented
return tuple(self.items()) == tuple(other.items())
__hash__ = None
def __ne__(self, other):
"Return self!=other"
if not isinstance(other, OrderedPyDict):
return NotImplemented
return tuple(self.items()) != tuple(other.items())
def __repr__(self):
"Return repr(self)"
if len(self) == 0:
return "OrderedPyDict()"
if id(self) in _repr_pydicts:
return "OrderedPyDict([...])"
_repr_pydicts.add(id(self))
parts = []
for key, value in self.items():
parts.append(repr((key, value)))
_repr_pydicts.remove(id(self))
return "OrderedPyDict([" + ", ".join(parts) + "])"
__slots__ = ()
#####################################################
### defaultpydict
####################################################
class defaultpydict(pydict):
"""Python dictionary with an optional default factory when __getitem__ fails due to a KeyError
defaultpydict(default_factory[, ...]) -> new default pydict with its default factory set to default_factory
For other combinations of constructor arguments see help(pydict).
"""
def __missing__(self, key):
"Fallback method when self[key] fails."
factory = self.default_factory
if callable(factory):
return factory()
raise KeyError(key)
def __new__(cls, default_factory=None, mapping_or_iterable=(), /, **kwds):
# Get a raw pydict
self = pydict.__new__(cls, mapping_or_iterable, **kwds)
# Assign a default factory
self.default_factory = default_factory
# Return self
return self
def __repr__(self):
"Return repr(self)"
if id(self) in _repr_pydicts:
return "defaultpydict(..., pydict({...}))"
s = pydict.__repr__(self)
_repr_pydicts.add(id(self))
s = repr(self.default_factory) + ", " + s
_repr_pydicts.remove(id(self))
return "defaultpydict(" + s + ")"
__slots__ = ("_default_factory",)
@property
def default_factory(self):
"Factory for default value called by __missing__"
return getattr(self, "_default_factory", None)
@default_factory.setter
def default_factory(self, value):
self._default_factory = value
######################################################
### ShallowChainMap
######################################################
class ShallowChainMap(pydict):
''' A ShallowChainMap groups multiple pydicts (or other mappings) together
to create a single, updateable view.
The underlying mappings are stored in a list. That list is public and can
be accessed or updated using the *maps* attribute. There is no other
state.
Lookups search the underlying mappings successively until a key is found.
In contrast, writes, updates, and deletions only operate on the first
mapping.
'''
__slots__ = ("_maps",)
def __new__(cls, *maps):
self = pydict.__new__(cls)
self.maps = list(maps) or [pydict()]
self._keys = self._hash_table = self._size = None
return self
def __getitem__(self, key):
for map in self.maps:
try:
return map[key]
except KeyError:
pass
return self.__missing__(key)
def __len__(self):
return sum([len(map) for map in self.maps])
def as_pydict(self):
"Return self as a plain pydict."
pd = pydict()
for map in reversed(self.maps):
pd.update(map)
return pd
def __iter__(self):
return iter(self.as_pydict())
def __reversed__(self):
return reversed(self.as_pydict())
def __contains__(self, key):
return any([key in map for map in self.maps])
def __bool__(self):
"Return bool(self)."
return any(self.maps)
def __repr__(self):
if id(self) in _repr_pydicts:
return f"{self.__class__.__name__}(...)"
_repr_pydicts.add(id(self))
s = f"{self.__class__.__name__}({', '.join([repr(map) for map in self.maps])})"
_repr_pydicts.remove(id(self))
return s
def copy(self):
"Return a new ShallowChainMap or subclass. \nIts first map is copied, while other mappings remain intact."
return self.__class__(self.maps[0].copy(), *self.maps[1:])
@property
def maps(self):
"A mutable list of this ShallowChainMap's maps"
if not hasattr(self, '_maps'):
self._maps = [pydict()]
return self._maps
@maps.setter
def maps(self, value):
value = list(value)
if not value:
self._maps = [pydict()]
return
for item in value:
if not isinstance(item, _collections_abc.Mapping):
raise TypeError(f"All items of maps list must be instances of collections.abc.Mapping, " + \
f"not {item.__class__.__module__}.{item.__class__.__name__}")
self._maps = value
def child(self, map=None):
"Return PyChainMap(map, *self.maps). \nIf map not given, it defaults to an empty pydict."
if map is None:
map = pydict()
return self.__class__(map, *self.maps)
@property
def parent(self):
"Returns PyChainMap(*self.maps[1:])"
return self.__class__(*self.maps[1:])
def __setitem__(self, key, value):
self.maps[0][key] = value
def __delitem__(self, key):
try:
del self.maps[0][key]
except KeyError:
raise KeyError(f"{key} not found in the first mapping.")
def __sizeof__(self):
# _keys, _hash_table, and _size are None
# _maps list can be accessed through maps property
# Therefore, no private internals to be accounted for
return object.__sizeof__(self)
def popitem(self, last=True):
"""Removes a key from the first mapping, return a 2-tuple: (the key, its associated value).
Raises KeyError if the first mapping is empty.
By default, the last key is removed.
When the first mapping's popitem supports the last argument, if bool(last)
evaluates to False, the first key is removed instead."""
try:
try:
return self.maps[0].popitem(last)
except TypeError:
return self.maps[0].popitem()
except KeyError:
raise KeyError("first mapping is empty.")
def clear(self):
"Clear the first mapping."
self.maps[0].clear()
def keys(self):
return self.as_pydict().keys()
def values(self):
return self.as_pydict().values()
def items(self):
return self.as_pydict().items()
##################################
### DeepChainMap
##################################
class DeepChainMap(ShallowChainMap):
"""A ShallowChainMap where writes, updates, and deletions operate
on all mappings, not just the first."""
def copy(self):
"Create a new DeepChainMap, with all maps copied."
c = []
for map in self.maps:
try:
c.append(map.copy())
except AttributeError:
c.append(map)
return DeepChainMap(*c)
def clear(self):
"Clear all mappings."
for map in self.maps:
try:
map.clear()
except Exception:
pass
def popitem(self, last=True):
"""Removes a key from the first non-empty mapping, return a 2-tuple: (the key, its associated value).
Raises KeyError if all mappings are empty.
By default, the last key is removed.
When the first non-empty mapping's popitem supports the last argument, if bool(last)
evaluates to False, the first key is removed instead."""
for map in self.maps:
try:
try:
return map.popitem(last)
except TypeError:
return map.popitem()
except KeyError:
pass
raise KeyError(key)
def __delitem__(self, value):
for map in self.maps:
try:
del map[value]
return
except KeyError:
pass
raise KeyError(key)
def __setitem__(self, key, value):
for mapping in self.maps:
if key in mapping:
mapping[key] = value
return
self.maps[0][key] = value
__slots__ = ()
##################################
### Final touches, testing
##################################
__all__ = [i for i in globals() if i[0] != "_"]
##########################################
### End important part of module
###########################################
# Views and iterators. No need to export.
####################################################
### views
####################################################
class PyDictView(object):
def __contains__(self, key):
"Return key in self."
return key in list(self)
def __iter__(self):
"Return iter(self)."
return PyDictIterator(self._mapping)
def __len__(self):
"Return len(self)."
return len(self._mapping)
def __new__(cls, mapping=None):
if _sys._getframe(1).f_globals is not globals():
raise TypeError(f"Cannot create {cls.__name__} instances")
self = object.__new__(cls)
self._mapping = mapping
return self
def __repr__(self):
"Return repr(self)."
return f"{self.__class__.__name__}({list(self)})"
def __reversed__(self):
"Return reversed(self)."
return PyDictReverseIterator(self._mapping)
__slots__ = ('_mapping',)
@property
def mapping(self):
"Return a read-only version of the original pydict/frozenpydict."
if isinstance(self._mapping, frozenpydict):
return self._mapping
return frozenpydict(self._mapping)
class PyDictSetView(PyDictView):
"Base class of PyDictViews which implements some set functionality."
def __and__(self, other):
"Return self&other"
if not isinstance(other, _collections_abc.Iterable):
return NotImplemented
return {i for i in self if i in other}
def __eq__(self, other):
"Return self==other"
if not isinstance(other, _collections_abc.Iterable):
return NotImplemented
return self <= other and len(self) == len(other)