My point mainly is just that it’s not obvious what - should do
Diff should be its own method for sure
My point mainly is just that it’s not obvious what - should do
Diff should be its own method for sure
Also the |
is not obvious, and you need to specificly learn that keys from the second dict override the ones from the first one.
But it is USEFUL and easy to use, which gives a good enough reason to implement it.
The same argument is valid for the -
operator.
בתאריך שבת, 19 באוק׳ 2024, 19:19, מאת James Campbell via Discussions on Python.org <notifications@python1.discoursemail.com>:
IMHO, for the reasons already described by other people, more logical and less confusing would be to restrict the operand’s type to set-like ones:
>>> {'a': 1, 'c': 42} - {'a'}
{'c': 42}
>>> {'a': 1, 'c': 42} - {'a': 2}.keys()
{'c': 42}
>>> d = {'a': 1, 'c': 42}
>>> d -= {'a': 2}.keys()
>>> d
{'c': 42}
And, perhaps, it’d be a good idea to:
-
operator’s second operand just to instances of: set
, frozenset
and type({}.keys())
;-=
operator more liberal (as it is the case for |=
vs. |
…) – in this case: accepting any (actual and “virtual”) instances of collections.abc.Set
, or perhaps even just any iterables (but in the latter variant, we have again the potentially confusing dict - dict
case…).Why not restricting simply to any instance of collections.abc.Set
?
The problem with d.keys() - other_dict.keys()
is that it creates a set
, that is not ordered, so the new dict
does not preserve the order of the old dict
.
Maybe if the stdlib includes an ordered set
it can be done, but unluckily Python don’t have it now.
Notice that you don’t have this problem with -=
, since you can simply pop the keys inplace.
About worthiness, it’s a matter of use case. I remember that’s a site you can search for code, but I forgot the name.
I’d find this syntax confusing if you don’t allow both subtracting a set and subtracting a dict. The most natural compromise that allows both of those us to allow all iterators.
I understand there’s concerns about the performance, and I would expect that type-forcing the iterator into a set would be a good enough solution. The situation where you do small_dict - big_set
is one where it is relatively intuitive that you might need to call a special method to optimise performance.
That said, if this doesn’t get implemented at all it won’t bother me personally either.
It’s not an hard constraint. Instead of doing d - other_d
we have to write d - other_d.keys()
. It enforces strong typing, avoid confusion about the role of other_d
values and improve performance, because you know that the RHS is formed by unique, hashable objects. For any other iterable, instead of writing d - it
we can simply write d - set(it)
.
On the other hand, if we allow dict - iterable
, why not extend this to set
?