This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

Author Zahari.Dim
Recipients Zahari.Dim
Date 2018-09-05.14:00:10
SpamBayes Score -1.0
Marked as misclassified Yes
Message-id <1536156010.09.0.56676864532.issue34586@psf.upfronthosting.co.za>
In-reply-to
Content
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.
History
Date User Action Args
2018-09-05 14:00:10Zahari.Dimsetrecipients: + Zahari.Dim
2018-09-05 14:00:10Zahari.Dimsetmessageid: <1536156010.09.0.56676864532.issue34586@psf.upfronthosting.co.za>
2018-09-05 14:00:10Zahari.Dimlinkissue34586 messages
2018-09-05 14:00:10Zahari.Dimcreate