File tree Expand file tree Collapse file tree 1 file changed +51
-0
lines changed
Expand file tree Collapse file tree 1 file changed +51
-0
lines changed Original file line number Diff line number Diff line change 1+ """
2+ an exploration of how the dict constructor knows whether it is
3+ working with a MApping of a general iterable. It looks like
4+ the code is something like this:
5+
6+ if isinstance(input, collections.abc.Mapping):
7+ self.update = {key: input[key] key in input}
8+ else:
9+ self.update = {key: val for key, val in input}
10+
11+ So if your custom class present themapping interface -- that is, iterating
12+ over it returns the keys, than you want to be a MApping ABC subclass.ABC
13+
14+ But if your custom class is not a Mapping, then you want __iter__ to return an
15+ iterator over teh key, value pairs.
16+ """
17+
18+ from collections .abc import Mapping
19+
20+
21+ def test_iter (instance ):
22+ yield ("this" )
23+ yield ("that" )
24+
25+
26+ class DictTest (Mapping ):
27+
28+ def __init__ (self , this = "this" , that = "that" ):
29+ self .this = this
30+ self .that = that
31+
32+ def __iter__ (self ):
33+ print ("iter called" )
34+ return test_iter (self )
35+
36+ def __getitem__ (self , key ):
37+ return getattr (self , key )
38+
39+ def __len__ (self ):
40+ print ("__len__ called" )
41+
42+
43+ if __name__ == "__main__" :
44+
45+ dt = DictTest ()
46+ print (dict (dt ))
47+
48+ dt = DictTest (this = 45 , that = 654 )
49+ print (dict (dt ))
50+
51+
You can’t perform that action at this time.
0 commit comments