[Python-ideas] Have dict().update() return its own reference.

Masklinn masklinn at masklinn.net
Sat Apr 21 14:53:27 CEST 2012

On 2012-04-21, at 02:24 , Steven D'Aprano wrote:

> Masklinn wrote:
>> On 2012-04-20, at 23:41 , Paul Moore wrote:
>>> On 20 April 2012 20:49, Masklinn <masklinn at masklinn.net> wrote:
>>>> If they're huge mappings, you probably don't want to go around copying
>>>> them either way[0] and would instead use more custom mappings, either
>>>> some sort of joining proxy or something out of Okasaki (a clojure-style
>>>> tree-based map with structural sharing for instance)
>>> Python 3.3 has collections.ChainMap for this sort of case.
>> Yeah, it's an example of the "joining proxy" thing. Though I'm not sure
>> I like it being editable, or the lookup order when providing a sequence
>> of maps (I haven't tested it but it appears the maps sequence is traversed
>> front-to-back, I'd have found the other way around more "obvious", as if
>> each sub-mapping was applied to a base through an update call).
> ChainMap is meant to emulate scoped lookups

yes, my notes were in the context of the thread considering chainmap as a
proxy for multiple mappings, I understand this was not the primary use case
for chainmap

> , e.g. builtins + globals + nonlocals + locals. Hence, newer scopes mask older scopes. "Locals" should be fast, hence it is at the front.

That's just a question of traversal order for the maps sequence, if the sequence
is in the order you specify there: [builtins, globals, nonlocals, locals] then it
can be traversed from the back for locals to have the highest priority. The difference
in speed should be almost nil

> As for being editable, I'm not sure what you mean here, but surely you don't object to it being mutable?

I do, though again that's considering the usage of chainmap as a proxy, not
as a scope chain.

>> An other potential weirdness of this solution — I don't know how ChainMap
>> behaves there, the documentation is unclear — is iteration over the map
>> and mapping.items() versus [(key, mapping[key]) for key in mapping]
>> potentially having very different behaviors/values since the former is
>> going to return all key:value pairs but the latter is only going to return
>> the key:(first value for key) pairs which may lead to significant repetitions
>> any time a key is present in multiple contexts.
> No, iteration over the ChainMap returns unique keys, not duplicates.

Ah, that's good. Would probably warrant mention in the documentation though.

More information about the Python-ideas mailing list