Message129483
| Author |
rhettinger |
| Recipients |
alex, daniel.urban, eric.araujo, pitrou, r.david.murray, rhettinger |
| Date |
2011年02月26日.01:13:03 |
| SpamBayes Score |
2.8969245e-05 |
| Marked as misclassified |
No |
| Message-id |
<1298682784.22.0.640219863058.issue11297@psf.upfronthosting.co.za> |
| In-reply-to |
| Content |
I was thinking of adding a recipes section to show how to extend or override the class:
class DjangoContext(ChainMap):
def push(self):
self.maps.insert(0, {})
def pop(self):
self.maps.pop(0)
class NestedScope(ChainMap):
'Mutating methods that write to first matching dict'
def __setitem__(self, key, value):
'''Find the first matching *key* in chain and set its value.
If not found, sets in maps[0].
'''
for m in self.maps:
if key in m:
break
else:
m = self.maps[0]
try:
cs = m.chain_set
except AttributeError:
m[key] = value
else:
cs(key, value)
def __delitem__(self, key):
'''Find and delete the first matching *key* in the chain.
Raise KeyError if not found.
'''
for m in self.maps:
if key in m:
break
try:
cd = m.chain_del
except AttributeError:
del m[key]
else:
cd(key)
def popitem(self):
for m in self.maps:
if m:
break
return m.popitem()
def clear(self):
for m in self.maps:
m.clear() |
|