[Python-ideas] Dict joining using + and +=
2QdxY4RzWzUUiLuE at potatochowder.com
Mon Mar 4 18:49:41 EST 2019
On 3/4/19 5:11 PM, Steven D'Aprano wrote:
> On Mon, Mar 04, 2019 at 11:56:54AM -0600, Dan Sommers wrote:
>> On 3/4/19 10:44 AM, Steven D'Aprano wrote:
>> > If you know ahead of time which order you want, you can simply reverse
>> > it:
>> > # prefs = site_defaults + user_defaults + document_prefs
>> > prefs = dict(ChainMap(document_prefs, user_defaults, site_defaults))
>> > but that seems a little awkward to me, and reads backwards. I'm used to
>> > thinking reading left-to-right, not right-to-left.
>> I read that as use document preferences first, then user
>> defaults, then site defautls, exactly as I'd explain the
>> functionality to someone else.
> If you explained it to me like that, with the term "use", I'd think that
> the same feature would be done three times: once with document prefs,
> then with user defaults, then site defaults.
> Clearly that's not what you mean, so I'd then have to guess what you
> meant by "use", since you don't actually mean use. That would leave me
> trying to guess whether you meant that *site defaults* overrode document
> prefs or the other way.
> I don't like guessing, so I'd probably explicitly ask: "Wait, I'm
> confused, which wins? It sounds like site defaults wins, surely that's
> not what you meant."
You're right: "use" is the wrong word. Perhaps "prefer"
is more appropriate. To answer the question of which wins:
the first one in the list [document, user, site] that
contains a given preference in question. Users don't see
dictionary updates; they see collections of preferences in
order of priority.
Documentation is hard. :-)
>> So maybe we're agreeing: if you think in terms of updating
>> a dictionary of preferences, then maybe it reads backwards,
>> but if you think of implementing features, then adding
>> dictionaries of preferences reads backwards.
> Do you think "last seen wins" is backwards for dict.update() or for
> command line options?
As a user, "last seen wins" is clearly superior for command
line options. As a programmer, because object methods
operate on their underlying object, it's pretty obvious that
d1.update(d2) starts with d1 and applies the changes
expressed in d2, which is effectively "last seen wins."
If I resist the temptation to guess in the face of
ambiguity, though, I don't think that d1 + d2 is any less
ambiguous than a hypothetical dict_update(d1, d2) function.
When I see a + operator, I certainly don't think of one
operand or the other winning.
More information about the Python-ideas