Suggestion: make sequence and map interfaces more similar

Chris Angelico rosuav at gmail.com
Tue Mar 29 20:56:33 EDT 2016


On Wed, Mar 30, 2016 at 9:29 AM, Marco Sulla via Python-list
<python-list at python.org> wrote:
> On 29 March 2016 at 16:31, Chris Angelico <rosuav at gmail.com> wrote:
>> But the definition of a sequence, and likewise the definition of a
>> mapping, goes deeper than that. A sequence has *relative* stability;
>> if one item is at a lower index than another, it will continue to be
>> at a lower index, until you change one of those two items. Changes
>> elsewhere in the sequence might bring them closer together or push
>> them further apart, but one of them is still earlier in the sequence
>> than the other. A mapping, on the other hand, has *absolute*
>> stability. Any given key->value relationship is stable in and of
>> itself. If you stuff a thing into a dict under a particular key, you
>> expect to be able to get it back using that key, not some other.
>
> It's the same arguments of Steven D'Aprano. Let me counter these
> arguments with this example:
>
>>>> class StrangeDict(dict):
> ...     def insert(self, k, v):
> ...         if k in self:
> ...             for key in [x for x in sorted(self.keys()) if x >= k]:
> ...                 v_next = self[key]
> ...                 self[key] = v
> ...                 v = v_next
> ...
> ...             self[key+1] = v
> ...
>>>> a = StrangeDict({0:5, 1:7, 2: 14})
>>>> a.insert(1, 5)
>>>> a
> {0: 5, 1: 5, 2: 7, 3: 14}
>
> Yes, it's a terrible class and lacks a lot of safety checks, but I
> don't think at all it violates the map contract. You can continue and
> add some constraint at __init__() about key types and their
> contiguity, some other methods and voila', you'll get a list-like
> class.

The map contract is this:

x = StrangeDict()
x[123] = 456
...
assert x[123] == 456

Your mapping does violate the map contract.

ChrisA



More information about the Python-list mailing list