osdir.com


[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

[Python-Dev] Proposal: dict.with_values(iterable)


On 22Apr2019 2119, Glenn Linderman wrote:
> While Inada's suggested DictBuilder interface was immediately obvious, I 
> don't get how either copy or update would achieve the goal. Perhaps you 
> could explain? Particularly, what would be the trigger that would make 
> dict() choose to create a shared key dictionary from the start? Unless 
> it is known that there will be lots of (mostly static) dictionaries with 
> the same set of keys at the time of creation of the first one, creating 
> a shared key dictionary in every case would cause later inefficiencies 
> in converting them, when additional items are added? (I'm assuming 
> without knowledge that a single shared key dictionary is less efficient 
> than a single regular dictionary.)

Passing a dictionary to the dict() constructor creates a copy of that 
dictionary (as does copy.copy()). What other trigger do you need to 
decide "it contains the same keys"? It's a copy of the original dict, so 
by definition at that point it may as well share its entire contents 
with the original.

Basically this is just a partial copy-on-write, where we copy values 
eagerly - since they're almost certainly going to change - and keys 
lazily - since there are known scenarios where they are not going to be 
changed, but we'll pay the cost later if it turns out they are.

Cheers,
Steve