Suggestion: make sequence and map interfaces more similar
Peter Otten
__peter__ at web.de
Wed Mar 23 05:10:54 EDT 2016
Marco S. via Python-list wrote:
> I noticed that the sequence types does not have these methods that the map
> types has: get(), items(), keys(), values().
> It could seem useless to have them for sequences, but I think it will ease
> the creation of functions and methods that allow you to input a generic
> iterable as parameter, but needs to use one of these methods in case the
> parameter is a map.
>
> In one word, it will facilitate duck typing.
It will also break existing uses of duck typing. The first one I found:
>>> class List(list):
... def items(self):
... return list(enumerate(self))
...
>>> from urllib.parse import urlencode
>>> urlencode([("a", "b"), ("c", "d")])
'a=b&c=d'
>>> urlencode(List([("a", "b"), ("c", "d")]))
'0=%28%27a%27%2C+%27b%27%29&1=%28%27c%27%2C+%27d%27%29'
> For the same reason, I would suggest the introduction of a new map type,
> vdict, a dict that by default iterates over values instead over keys. So a
> vdict object "d" wiil have iter(d) == iter(d.values()), and should also
> have a count() method, like sequence types.
>
> Indeed sequences are, in my humble opinion, a specialized case of maps,
> when keys are numeric only, are always contiguous without gaps and start
> from 0. This way we will have a simpler way to let people to use sequences
> or maps indifferently, and let the code untouched.
Can you provide a few examples where this has /practical/ advantages?
Isn't allowing
some_list.get("key")
more likely to hide programming errors than to make code more generic in a
useful way?
More information about the Python-list
mailing list