dict.update() to take dict, add update_items() to take iterable?
dict.update() takes an iterable:
protocol Mapping[A(Eq),B] (Container[A], Indexed[A,B]):
update : mut(Iterable[(A,B)]) -> None
this is weird because we write:
d = {}
d.update({"foo": "bar"}.items())
it would be more natural to not have to do .items(), like so:
d = {}
d.update({"foo": "bar"})
should we change update to take a Mapping instead? We know Mapping supports items.
We can add a update_items() method that acts as the current .update() in case someone has a different source of items to update.
@sydow @nordlander WDYT?
Hi,
I don’t have strong opinions here. I agree that your examples looks a bit clumsy, but why build a dict of new elements here? You can write
d = {} d.update([(“foo”,”bar”)]
which seems more natural to me (even more so, if you add several pairs). In the situation where you actually already have a dict that you want to merge with another one, you will have to write d1.update(d2.items()), but I don’t think that is a high price to pay.
Another possibility would be to think again about the protocols and make dict[(A,B)] implement Iterable[(A,B)] (rather than, as now Iterable[A] via Container[A]). I have not thought through this…
Björn
On 23 Dec 2024, at 11:21, Kristian Larsson @.***> wrote:
dict.update() takes an iterable: protocol Mapping[A(Eq),B] (Container[A], Indexed[A,B]): update : mut(Iterable[(A,B)]) -> None
this is weird because we write: d = {} d.update({"foo": "bar"}.items())
it would be more natural to not have to do .items(), like so: d = {} d.update({"foo": "bar"})
should we change update to take a Mapping instead? We know Mapping supports items. We can add a update_items() method that acts as the current .update() in case someone has a different source of items to update. @sydow @nordlander WDYT? — Reply to this email directly, view it on GitHub, or unsubscribe. You are receiving this because you were mentioned.Message ID: @.***>
Isn't the core problem that we've followed Python's view that iteration over a dict means iterating over its keys only? Instead, if Mapping[A,B] would inherit Container[(A,B)] and not Container[A], the update ugliness would go away I think.
The downside would of course be that x in some_dict then must mean checking whether some key-value pair is in some_dict. Perhaps not that useful, but maybe one could find a way to keep the Python meaning in this particular case...
Oop, overlapping with Björn's comment. Sorry...!