File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change @@ -100,6 +100,21 @@ The class can be used to simulate nested scopes and is useful in templating.
100100 :func: `super ` function. A reference to ``d.parents `` is equivalent to:
101101 ``ChainMap(*d.maps[1:]) ``.
102102
103+ Note, the iteration order of a :class: `ChainMap() ` is determined by
104+ scanning the mappings last to first::
105+
106+ >>> baseline = {'music': 'bach', 'art': 'rembrandt'}
107+ >>> adjustments = {'art': 'van gogh', 'opera': 'carmen'}
108+ >>> list(ChainMap(adjustments, baseline))
109+ ['music', 'art', 'opera']
110+
111+ This gives the same ordering as a series of :meth: `dict.update ` calls
112+ starting with the last mapping::
113+
114+ >>> combined = baseline.copy()
115+ >>> combined.update(adjustments)
116+ >>> list(combined)
117+ ['music', 'art', 'opera']
103118
104119.. seealso ::
105120
Original file line number Diff line number Diff line change @@ -113,6 +113,20 @@ def test_basics(self):
113113 self .assertEqual (f ['b' ], 5 ) # find first in chain
114114 self .assertEqual (f .parents ['b' ], 2 ) # look beyond maps[0]
115115
116+ def test_ordering (self ):
117+ # Combined order matches a series of dict updates from last to first.
118+ # This test relies on the ordering of the underlying dicts.
119+
120+ baseline = {'music' : 'bach' , 'art' : 'rembrandt' }
121+ adjustments = {'art' : 'van gogh' , 'opera' : 'carmen' }
122+
123+ cm = ChainMap (adjustments , baseline )
124+
125+ combined = baseline .copy ()
126+ combined .update (adjustments )
127+
128+ self .assertEqual (list (combined .items ()), list (cm .items ()))
129+
116130 def test_constructor (self ):
117131 self .assertEqual (ChainMap ().maps , [{}]) # no-args --> one new dict
118132 self .assertEqual (ChainMap ({1 :2 }).maps , [{1 :2 }]) # 1 arg --> list
You can’t perform that action at this time.
0 commit comments