Author rhettinger
Recipients alex, daniel.urban, eric.araujo, pitrou, r.david.murray, rhettinger
Date 2011-02-26.01:13:03
SpamBayes Score 2.89692e-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()
History
Date User Action Args
2011-02-26 01:13:04rhettingersetrecipients: + rhettinger, pitrou, eric.araujo, alex, r.david.murray, daniel.urban
2011-02-26 01:13:04rhettingersetmessageid: <1298682784.22.0.640219863058.issue11297@psf.upfronthosting.co.za>
2011-02-26 01:13:03rhettingerlinkissue11297 messages
2011-02-26 01:13:03rhettingercreate