Suggestion: make sequence and map interfaces more similar

Steven D'Aprano steve+comp.lang.python at pearwood.info
Wed Mar 30 01:43:23 EDT 2016


On Wednesday 30 March 2016 14:38, Random832 wrote:

> On Tue, Mar 29, 2016, at 20:56, Chris Angelico wrote:
>> The map contract is this:
>> 
>> x = StrangeDict()
>> x[123] = 456
>> ...
>> assert x[123] == 456
>> 
>> Your mapping does violate the map contract.
> 
> So, you can put *anything* in that "..."?

Yes, we're all very impressed that you spotted the trivial and obvious 
loophole that changing a key:value will change the key:value that you just 
changed *wink* but that doesn't really move the discussion anywhere.

This is not an argument about dicts being mutable, because clearly they 
aren't. This is an argument about key:value pairs being stable. "Stable" 
doesn't mean "immutable". If you change the value associated with a key 
directly, then it will change. That's the whole point. But if you change 
*one* key, the relationship between *other* keys and their values shouldn't 
change.

Given a surjection (many-to-one mapping) between keys and values in a 
mapping, we expect that changing the mapping of one key will not affect 
other keys. To be pedantic, by "change" I mean deleting the key (and, if 
necessary, value) or reassigning a new value to the key. To be even more 
pedantic, mutations to the value *do not count*.

Specifically, insertions and deletions to the mapping never affect the 
existing keys. But, critically, insertions and deletions to a sequence do 
sometimes affect the index of existing items.

So while we can say that there is a surjective function that maps the index 
of a sequence to an item, but that relationship fails to meet the 
requirements for it to be a mapping type like a dict.

https://en.wikipedia.org/wiki/Bijection,_injection_and_surjection


If somebody wants to insist that this is a kind of mapping, I can't 
disagree, but it isn't useful as a mapping type.



-- 
Steven




More information about the Python-list mailing list