New submission from Zahari Dim <zaha...@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 <rep...@bugs.python.org>
<https://bugs.python.org/issue34586>
_______________________________________
_______________________________________________
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com

Reply via email to