-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathdict_making.py
More file actions
51 lines (33 loc) · 1.13 KB
/
dict_making.py
File metadata and controls
51 lines (33 loc) · 1.13 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
"""
an exploration of how the dict constructor knows whether it is
working with a MApping of a general iterable. It looks like
the code is something like this:
if isinstance(input, collections.abc.Mapping):
self.update = {key: input[key] key in input}
else:
self.update = {key: val for key, val in input}
So if your custom class present themapping interface -- that is, iterating
over it returns the keys, than you want to be a MApping ABC subclass.ABC
But if your custom class is not a Mapping, then you want __iter__ to return an
iterator over teh key, value pairs.
"""
from collections.abc import Mapping
def test_iter(instance):
yield ("this")
yield ("that")
class DictTest(Mapping):
def __init__(self, this="this", that="that"):
self.this = this
self.that = that
def __iter__(self):
print("iter called")
return test_iter(self)
def __getitem__(self, key):
return getattr(self, key)
def __len__(self):
print("__len__ called")
if __name__ == "__main__":
dt = DictTest()
print(dict(dt))
dt = DictTest(this=45, that=654)
print(dict(dt))