New submission from Zahari Dim <>:

When using ChainMap I have frequently needed to know the mapping inside the list
that contains the effective instance of a particular key. I have needed this
when using ChainMap to contain a piece of configuration with multiple sources,
like for example

from mycollections import ChainMap
configsources = ["Command line", "Config file", "Defaults"]
config = ChainMap(config_from_commandline(), config_from_file(),

class BadConfigError(Exception): pass
def get_key(key):
        index, value = config.get_where(key)
    except KeyError as e:
        raise BadConfigError(f"No such key: '{key}'") from e
        result = validate(key, value)
    except ValidationError as e:
        raise BadConfigError(f"Key '{key}' defined in {configsources[index] }"
                             f"is invalid: {e}") from e
    return result

I have also needed this when implementing custom DSLs (e.g. specifying which
context is a particular construct allowed to see).

I think this method would be generally useful for the ChainMap class and
moreover the best way of implementing it I can think of is  by copying the
`__getitem__` method and retaining the index:

class ChainMap(collections.ChainMap):
    def get_where(self, key):
        for i, mapping in enumerate(self.maps):
                return i, mapping[key]             # can't use 'key in mapping' 
with defaultdict
            except KeyError:
        return self.__missing__(key)            # support subclasses that 
define __missing__

I'd be happy to write a patch that does just this.

components: Library (Lib)
messages: 324632
nosy: Zahari.Dim
priority: normal
severity: normal
status: open
title: collections.ChainMap should have a get_where method
type: enhancement
versions: Python 3.8

Python tracker <>
Python-bugs-list mailing list

Reply via email to