Message324632
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. |
|
Date |
User |
Action |
Args |
2018-09-05 14:00:10 | Zahari.Dim | set | recipients:
+ Zahari.Dim |
2018-09-05 14:00:10 | Zahari.Dim | set | messageid: <1536156010.09.0.56676864532.issue34586@psf.upfronthosting.co.za> |
2018-09-05 14:00:10 | Zahari.Dim | link | issue34586 messages |
2018-09-05 14:00:10 | Zahari.Dim | create | |
|