[issue11297] Make ChainMap() public in the collections module.

Raymond Hettinger report at bugs.python.org
Sat Feb 26 02:13:04 CET 2011


Raymond Hettinger <rhettinger at users.sourceforge.net> added the comment:

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()

----------

_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue11297>
_______________________________________


More information about the Python-bugs-list mailing list