-
-
Notifications
You must be signed in to change notification settings - Fork 31.1k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
ChainMap.new_child could use improvement #60817
Comments
ChainMap.new_child could IMO be improved through allowing an optional dict to be passed, which is used to create the child. The use case is that you sometimes need to temporarily push a new non-empty mapping in front of an existing chain. This could be achieved by changing new_child to the following, which is backwards-compatible: def new_child(self, d=None):
'New ChainMap with a new dict followed by all previous maps.'
return self.__class__(d or {}, *self.maps) |
I agree that this would be useful. |
I'd like to have this feature too. However the code should use d if d is not None else {} instead of d or {} For example I might want to use a subclass of dict (lowerdict) that converts all keys to lowercase. When I use an empty lowerdict in new_child(), new_child() would silently use a normal dict instead: class lowerdict(dict):
def __getitem__(self, key):
return dict.__getitem__(
self,
key.lower() if isinstance(key, str) else key
)
import collections
cm = collections.ChainMap(lowerdict(), lowerdict())
cm2 = cm.new_child(lowerdict())
print(type(cm2.maps[0])) This would print <class 'dict'>. |
Your intention makes sense, though I would prefer to write it as: if d is None:
d = {}
return self.__class__(d, *self.maps) |
Can you write-up a patch with tests and a doc change? |
Done. |
Put a *versionchanged* tag in the doc entry and this is ready to apply. |
Also, please change the variable name from *amap* to either *m* or *mapping*. |
New changeset c0ddae67f4df by Vinay Sajip in branch 'default': |
Note: these values reflect the state of the issue at the time it was migrated and might not reflect the current state.
Show more details
GitHub fields:
bugs.python.org fields:
The text was updated successfully, but these errors were encountered: