Suggestion: make sequence and map interfaces more similar

Antoon Pardon antoon.pardon at rece.vub.ac.be
Thu Mar 31 04:04:04 EDT 2016


Op 31-03-16 om 04:44 schreef Steven D'Aprano:
> On Thu, 31 Mar 2016 03:52 am, Random832 wrote:
>
>> Like, these are common patterns:
>>
>> for i, x in enumerate(l):
>>    # do some stuff, sometimes assign l[i]
>>
>> for k, v in d.items():
>>    # do some stuff, sometimes assign d[k]
>
> for a, b in zip(spam, eggs):
>     # do some stuff, sometimes assign x[a] or b[a] or who knows what?
>
>
> Does this mean that "lists, dicts and zip" should all support the same
> interface?
>
> Not every coincidental and trivial piece of similar code is actually
> related.

But your addition shows that the similarities between lists and dicts
are greater than with zip. In the above two examples the assignment
was specific to elements of the list or dict over which was iterated.

Your x[a] and b[a] have no such relationship with the rest of your
example. This is further illustrated by the fact that your solution
doesn't provide a zip branch.

>> A way to apply that pattern generically to an object which may be either
>> a sequence or a mapping might be nice.
> Nice, and easy.
>
> # Duck-typing version.
> def iterpairs(obj):
>     if hasattr(obj, 'items'):
>         it = obj.items
>     else:
>         it = enum(obj)
>     yield from it
>
>
> # Type-checking version.
> def iterpairs(obj):
>     if isinstance(obj, collections.abc.Mapping):
>         it = obj.items
>     elif isinstance(obj, collections.abc.Sequence):
>         it = enum(obj)
>     else:
>         raise TypeError('not a sequence or a mapping')
>     yield from it
>
>
> Pick which one you prefer, stick it in your own personal toolbox of useful
> utilities functions, and off you go.
>
>
>
>




More information about the Python-list mailing list