[New-bugs-announce] [issue34586] collections.ChainMap should have a get_where method

Zahari Dim report at bugs.python.org
Wed Sep 5 10:00:10 EDT 2018


New submission from Zahari Dim <zaharid at gmail.com>:

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

class BadConfigError(Exception): pass
def get_key(key):
    try:
        index, value = config.get_where(key)
    except KeyError as e:
        raise BadConfigError(f"No such key: '{key}'") from e
    try:
        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):
            try:
                return i, mapping[key]             # can't use 'key in mapping' with defaultdict
            except KeyError:
                pass
        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 <report at bugs.python.org>
<https://bugs.python.org/issue34586>
_______________________________________


More information about the New-bugs-announce mailing list