[Python-ideas] get() method for list and tuples
Michel Desmoulin
desmoulinmichel at gmail.com
Tue Feb 28 20:26:18 EST 2017
Le 01/03/2017 à 01:02, Steven D'Aprano a écrit :
> On Tue, Feb 28, 2017 at 07:10:15PM +0100, Sven R. Kunze wrote:
>
>> 1. advantage: it looks like dict access -> allows duck typing (oh how
>> often I'd missed that)
>
> Dicts and lists don't duck-type because they are very different things.
>
> We know what ["item"]*10 does. What would {"key": "value"}*10 do?
>
> What would list.values() iterate over?
>
>
The fact the API is not exactly the same doesn't prevent duck typing.
Duck typing is precesily about incomplete but good enough similar API.
For the dict and list:
- you can iterate on both
- you can index both
- you can size both
Hence I can see very well functions working with both. E.G: helper to
extract x elements or a default value:
def extract(data, *args, default="None"):
for x in args:
try:
yield data[x]
except (KeyError, ValueError):
yield default
Usage:
a, b, c = extract(scores, "foo", "bar", "doh")
x, y, z = extract(items, 2, 5, 8, default=0)
I actually have this helper function.
With list.get and tuple.get, this would become:
def extract(data, *args, default="None"):
return (data.get(x, default) for x in args)
More information about the Python-ideas
mailing list